<?php

namespace App\Http\Services;

use App\Events\RoomRegisterEvent;
use App\Http\Model\ContentCheck;
use App\Http\Model\Device;
use App\Http\Model\Family;
use App\Http\Model\FinanceProxy;
use App\Http\Model\FormatCheck;
use App\Http\Model\Friends;
use App\Http\Model\GiftBag;
use App\Http\Model\Hint;
use App\Http\Model\Mall;
use App\Http\Model\OutJson;
use App\Http\Model\PropEvent;
use App\Http\Model\Room;
use App\Http\Model\RoomHostMicro;
use App\Http\Model\RoomUser;
use App\Http\Model\SystemConfig;
use App\Http\Model\Teenager;
use App\Http\Model\Union;
use App\Http\Model\UnionSigning;
use App\Http\Model\User;
use App\Http\Model\UserAccountCancel;
use App\Http\Model\UserFirstRechargeRecord;
use App\Http\Model\UserLoginLog;
use App\Http\Model\UserProp;
use App\Http\Model\UserRegisterLog;
use App\Http\Model\UserThirdpart;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\UserVerify;
use App\Http\Services\CoolNumberShoppingMall\ShoppingMallOrderServices;
use App\Lib\AppleJwtVerify;
use App\Lib\llqq;
use App\Lib\llwechat;
use App\Lib\oss;
use App\Lib\Publisher;
use App\Lib\qq;
use App\Lib\rc;
use App\Lib\ttwechat;
use App\Lib\hhwechat;
use App\Lib\wechat;
use App\Lib\weibo;
use App\Model\UserBlockLog;
use Illuminate\Support\Facades\Redis;
use function Composer\Autoload\includeFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Model\FinanceCharm;
use App\Http\Model\Gift;
use App\Http\Model\Trends;
use App\Http\Model\FinanceWealth;
use App\Http\Model\System;
use Exception;
use Illuminate\Support\Facades\Storage;
use App\Http\Services\SystemServices;
use App\Lib\Search;
use App\Http\Services\PlatformReportServices;
use App\Http\Model\Equip;
use App\Http\Model\Nameplate;
use App\Http\Services\ThinkingdataServices;
use App\Http\Model\UserAgent;
use App\Http\Model\RoomMicro;
use App\Http\Model\UserBlacklist;
use App\Http\Services\UserBlacklistServices;

/*用户service层*/
class UserServices extends CommonServices
{
    protected $passwordHash = 'kk-audio';
    protected $userWallet;
    protected $room;
    protected $user;
    private $model_friends;
    private $model_mall;
    private $model_roomuser;
    private $model_roomhostmicro;
    private $model_user_register_log;
    private $model_user_login_log;
    protected $modelFamily;

    protected $thirdWechat;
    protected $thirdLLWechat;
    protected $thirdTTWechat;
    protected $thirdHHWechat;
    protected $thirdQq;
    protected $thirdLLQq;
    protected $thirdWeibo;
    protected $thirdUser;
    protected $thirdAppleJwtVerify;
    private $lib_rong;
    protected $userPropModel;
    protected $modelDevice;
    protected $charm;
    protected $gift;
    protected $trends;
    protected $financeWealth;
    protected $model_finance_proxy;
    protected $modelUnion;
    protected $contentCheckModel;
    protected $unionSign;
    protected $modelUserVerify;
    protected $giftBagModel;
    private $jgConfig = [];//极光
    private $smConfig = [];//数美
    protected $teenager;
    protected $UserAccountCancelModel;
    private $system_service;
    protected $platformReportServices;
    protected $equipModel;
    protected $nameplateModel;
    protected $tdService;
    protected $userProtectModel;
    protected $userAgentModel;
    protected $userBlacklistService;
    protected $roomMicroModel;
    protected $mallGoods;
    private $userBlacklistModel;
    private $ChatFriendServices;
    private $userFirstRechargeModel;

    protected $firstRechargeData = [
        [
            "first_recharge_id" => "1",
            "title" => "6元礼包",
            "price" => 6,
            "diamond" => 200,
            "goods_list" => "167,168,169",
            "goods_list_sku" => "226,227,228",
            "purchase" => true,//true可以购买,false已购买
        ],
        [
            "first_recharge_id" => "2",
            "title" => "10元礼包",
            "price" => 10,
            "diamond" => 500,
            "goods_list" => "169,170,171",
            "goods_list_sku" => "228,229,230",
            "purchase" => true,
        ],
        [
            "first_recharge_id" => "3",
            "title" => "18元礼包",
            "price" => 18,
            "diamond" => 1000,
            "goods_list" => "171,172,173",
            "goods_list_sku" => "230,231,232",
            "purchase" => true,
        ],
    ];

    //房间主持麦用户
    private $redis_room_hostmicro_key = "ROOM:HOSTMICRO:"; //ROOM:HOSTMICRO:{room_id}

    //主播收礼实时榜单
    protected $anchorAcceptGiftTimeRankKey = 'ANCHORACCEPTGIFT:TIMERANK:';//zset ANCHORACCEPTGIFT:TIMERANK:{user_id} => {积分}=>{user_id}
    //主播收礼每日榜单
    protected $anchorAcceptGiftDayRankKey = 'ANCHORACCEPTGIFT:DAYRANK:';//zset ANCHORACCEPTGIFT:DAYRANK:{user_id}:{day} => {积分}=>{user_id}
    protected $prepare_img_key = 'USER:HEAD:PREOARE:';//用户预备头像 USER:HEAD:PREOARE:{$userId}=>{string}
    private $UserBlockLog;
    protected $redis_test_user_ids = 'CACHE:TEST:USERS';
    public function __construct()
    {
        parent::__construct();

        $this->UserAccountCancelModel =new UserAccountCancel();
        $this->userWallet = new FinanceUserWallet();
        $this->room = new Room();
        $this->user = new User();
        $this->thirdWechat = new wechat();
        $this->thirdLLWechat = new llwechat();
        $this->thirdTTWechat = new ttwechat();
        $this->thirdHHWechat = new hhwechat();
        $this->thirdQq = new qq();
        $this->thirdLLQq = new llqq();
        $this->thirdWeibo = new weibo();
        $this->thirdUser = new UserThirdpart();
        $this->model_friends = new Friends();
        $this->model_mall = new Mall();
        $this->lib_rong = new rc();
        $this->model_roomuser = new RoomUser();
        $this->model_roomhostmicro = new RoomHostMicro();
        $this->model_user_register_log = new UserRegisterLog();
        $this->model_user_login_log = new UserLoginLog();
        $this->userPropModel = new UserProp();
        $this->modelDevice = new Device();

        $this->charm = new FinanceCharm();
        $this->gift = new Gift();
        $this->trends = new Trends();
        $this->financeWealth = new FinanceWealth();

        $this->modelUnion = new Union();
        $this->unionSign = new UnionSigning();
        $this->contentCheckModel = new ContentCheck();
        $this->model_finance_proxy = new FinanceProxy();
        $this->jgConfig = config('jg');
        $this->smConfig = config('sumei');
        $this->thirdAppleJwtVerify = new AppleJwtVerify();
        $this->modelUserVerify = new UserVerify();
        $this->modelFamily = new Family();
        $this->giftBagModel = new GiftBag();
        $this->teenager = new Teenager();
        $this->system_service = new SystemServices();
        $this->platformReportServices = new PlatformReportServices();
        $this->equipModel = new Equip();
        $this->nameplateModel = new Nameplate();
        $this->tdService = new ThinkingdataServices();
        $this->userAgentModel = new UserAgent();
        $this->userBlacklistService = new UserBlacklistServices();
        $this->roomMicroModel = new RoomMicro();
        $this->userBlacklistModel = new UserBlacklist();
        $this->ChatFriendServices = new ChatFriendServices();
//        $this->UserBlockLog = new UserBlockLog();
        $this->userFirstRechargeModel = new UserFirstRechargeRecord();
        $this->mallGoods = new Mall();
    }

    //校验用户
    public function checkUserService($phone){
        $userObj = new User();
        $result = $userObj->get_user_by_phone($phone);
        if(!empty($result)){
            return false;
        }else{
            return true;
        }
    }

    //生成用户
    public function createUserService($phone, $password, $inviteUserId = 0, $isVisitor = 0, $nickname = '', $image = '', $inviteUserIdNew = 0)
    {
        $userId = $this->user->create($phone, $this->makeHashPassword($password), $inviteUserId, $isVisitor, $nickname, $image, $inviteUserIdNew);
        if ($userId > 0) {
            $this->user->set_current_user($userId);
        }
        return $userId;
    }

    //生成用户 无密码
    public function createUserNPwdService($phone, $inviteUserId = 0, $inviteUserIdNew = 0)
    {
        $userId = $this->user->create($phone, '', $inviteUserId, 0, '', '', $inviteUserIdNew);
        $this->user->set_current_user($userId);

        return $userId;
    }
    //生成账户
    public function createWalletService($userId){
        $wallet_id = $this->userWallet->add_wallet($userId);
        return $wallet_id;

    }



    //生成返回数据
    public function getResponseData($userId, $self = false){
        $userId = intval($userId);
        if(empty($userId)) {
            return [];
        }
        $userData = $this->user->get_user($userId, $self);
        if(empty($userData)) {
            return [];
        }
        if(!empty($userData)){
            $wallet = $this->userWallet->get_wallet($userData['user_id']);
            if(!empty($wallet)){
                $userData['diamond_balance'] = $wallet['diamond_balance'];
                $userData['charm_balance'] = $wallet['charm_balance'];
                $userData['wealth_balance'] = $wallet['wealth_balance'];
                $userData['kk_balance'] = $wallet['kk_balance'];
                $userData['pearl_balance'] = $wallet['pearl_balance'];
                $userData['reputation_balance'] = $wallet['reputation_balance'];
                $userData['celebrity_balance'] = $wallet['celebrity_balance'];
                $userData['hc_balance'] = $wallet['hc_balance'];
                $userData['jd_balance'] = $wallet['jd_balance'];
//                $userData['game_balance'] = $wallet['game_balance'];
                $userData['game_balance'] = empty($wallet['game_balance']) ? 1 : $wallet['game_balance'];
                $userData['agent_jd_balance'] = $wallet['agent_jd_balance'];
                $userData['debris_balance'] = $wallet['debris_balance'];
                $wealthRankList = $this->financeWealth->getWealthRankData();
                foreach($wealthRankList as $val) {
                    //用户当前等级
                    if($val['min_value']<=$wallet['wealth_balance'] && $wallet['wealth_balance']<=$val['max_value']) {
                        $userData['wealth_balance_image'] = $val['small_image'];
                        break;
                    }
                }

                $wealthCharmList=$this->charm->getNearCharmRank($wallet['charm_balance']);
                $userData['charm_balance_image'] = $wealthCharmList['small_image'];

            }
        }

        //检测用户是否已封禁
        $is_forbid = $this->user->is_forbid($userData['user_id']);
        if ($is_forbid && $is_forbid == 2){
            $userData['nickname'] = "该用户永久封禁";
            $userData['images'] = User::USER_DEFAULT_IMAGE;
            $userData['thumbnails'] = User::USER_DEFAULT_IMAGE;
        }

        $cur_user = $this->user->get_current_user();
        $userData['remark_name'] = !empty($cur_user['user_id']) ? $this->user->getUserRemark($cur_user['user_id'] ,$userId) : '';
        //审核功能相关

        //作品 音色+招牌
        $userData['teenager_lock'] = $this->teenager->getLock($userId);
        $userData['profile_percent'] = (new UserProfileServices())->getCompletion($userId);//用户资料完成度
        $userData['attires'] = $this->model_mall->getGoodsAttire($userId);
        $userData['show_full_screen_msg'] = (isset($userData['wealth_balance']) && $userData['wealth_balance'] >= 0);

        //用户头像审核状态
        $oldVerify = array_fill(0,count($userData['images']),1);
        $newVerify = [];
        //用户自己
        if ($cur_user && $cur_user['user_id'] == $userId) {
            // 用户本人，显示未审核的头像
            $checkImages = $this->getContentCheckAvatar($userId, $userData['images']);
            $userData['adapt_images'] = array_merge($userData['adapt_images'], $checkImages);
            $userData['images'] = array_merge($userData['images'], $checkImages);
            $userData['thumbnails'] = array_merge($userData['thumbnails'], $checkImages);
            $newVerify = array_fill(count($userData['images']),count($checkImages),0);
        }
        $userData['image_verify'] = array_merge($oldVerify,$newVerify);

        $userData['mood_name'] = '';
        $userData['mood_image'] = '';
        $userData['identity_role'] = empty($userData['identity_role']) ? 0 : $userData['identity_role'];
        $userData['identity_status'] = empty($userData['identity_status']) ? 0 : $userData['identity_status'];

        //获取用户正在使用的装备
        $userData['userEquip'] = $this->equipModel->getUserEquipByUserId($userId);

        //用户铭牌
        $userData['userNameplate'] = $this->nameplateModel->getNameplateByUserId($userId);

        //用户是否在房间锁麦
        $userData['micro_lock'] = (object) $this->roomMicroModel->getRoomLockMicroByUserId($userId);
        if(!empty($userData['micro_lock']->room_id)) {
            $roomInfo = $this->room->get_room($userData['micro_lock']->room_id);
            $userData['micro_lock']->room_name = empty($roomInfo['name']) ? '' : $roomInfo['name'];
        }

        //查询是否有达达返利的权限
        $userData['rebate_status'] = 0;

        $sysConfig = $this->system_service->get_config(); 
        $openStatus = isset($sysConfig['dd_rebate_button']) ? $sysConfig['dd_rebate_button']['value'] : 0;
        $rebateConfig = isset($sysConfig['dd_rebate_config']) ? json_decode($sysConfig['dd_rebate_config']['value'],true) : [];
        if(!empty($openStatus) && $rebateConfig['wealth_value'] <=  $userData['wealth_balance']){
            $userData['rebate_status'] = 1;//返利活动状态1=开启 0=关闭
        }

        // 用户身份
        $userData['user_type'] = 1; //1用户2主播

        $userType = $this->ChatFriendServices->getUserBlongToUinon($userId);
        if ($userType) {
            $userData['user_type'] = 2;
        }

        return $userData;
    }

    // 房间里获取用户信息
    public function getInRoomUserInfo($room_id, $userId, $self = false,$union_id=0, $loginUserId=0){
        $userData = $this->user->get_user($userId, $self);
        if(!empty($userData)){
            // 查询财富
            $wallet = $this->userWallet->get_wallet($userData['user_id']);
            if(!empty($wallet)){
                $userData['diamond_balance'] = $wallet['diamond_balance'];
                $userData['charm_balance'] = $wallet['charm_balance'];
                $userData['wealth_balance'] = $wallet['wealth_balance'];
                $userData['kk_balance'] = $wallet['kk_balance'];
                $userData['pearl_balance'] = $wallet['pearl_balance'];
                $userData['reputation_balance'] = $wallet['reputation_balance'];
                $userData['celebrity_balance'] = $wallet['celebrity_balance'];
                $userData['hc_balance'] = $wallet['hc_balance'];
                $userData['jd_balance'] = $wallet['jd_balance'];
//                $userData['game_balance'] = $wallet['game_balance'];
                $userData['game_balance'] = empty($wallet['game_balance']) ? 1 : $wallet['game_balance'];
                $userData['agent_jd_balance'] = $wallet['agent_jd_balance'];
                $userData['debris_balance'] = $wallet['debris_balance'];
            }

            // 是否关注
            $cur_user = $this->user->get_current_user();
            $userData['is_follow'] = $this->model_friends->get_follow_exist($cur_user['user_id'], $userId);
            $userData['fans_count'] = $this->model_friends->get_fans_count($userId);
            if (!empty($room_id)){
                $userData['room_block'] = $this->room->get_block($room_id, $userId);
            }

            $ua = $this->parse_app_UA();
            // 查询名片装扮
            $userData['mall_user_goods']['visiting_card'] = (object)[];
            $have_mall_user_goods = false;
            $getMallUserGoodsData = $this->model_mall->getGoodsAttire($userId);
            foreach ($getMallUserGoodsData as $value){
                // 名片
                if($value['goods_type'] == 4){
                    if(isset($value['animate_resource_big']) && empty($value['animate_resource_big'])){
                        unset($value['animate_resource_big']);
                    }
                    //ios 版本处理
                    if($ua['os_name'] == 'iPhone' && $ua['channel_id'] == 3000){
                        $value['animate_resource_small'] = '';
                    }
                    $userData['mall_user_goods']['visiting_card'] = $value;
                    $have_mall_user_goods = true;
                    break;
                }
            }
            if(!empty($union_id) && !$have_mall_user_goods){
                $user_consume = $this->modelUnion->getUserConsume($union_id ,$userId);
                if(!empty($user_consume['visit_image'])){
                    $temp['animate_resource']  = $user_consume['visit_image_double'];
                    $temp['animate_resource_small'] = $user_consume['visit_image'];
                    if(!empty($user_consume['visit_image_card'])){
                        $temp['animate_resource_big'] = $user_consume['visit_image_card'];
                    }
                    //ios 版本处理
                    if($ua['os_name'] == 'iPhone' && $ua['channel_id'] == 3000){
                        $temp['animate_resource_small'] = '';
                    }
                    $userData['mall_user_goods']['visiting_card'] = $temp;
                }
            }

            // 获取用户是否使用道具
            $propUseInfo = $this->userPropModel->getPropUseTime($userId, 15);
            $userData['user_prop']['hide_info'] = $propUseInfo ? true : false;
            //备注
            $userData['remark_name'] = $this->user->getUserRemark($cur_user['user_id'] ,$userId);
            //查询用户是否房间管理员，0:普通用户 1：管理员 2：房主
            $userData['role_type'] = $this->room->get_role($room_id, $userId);
            //查询用户装扮信息
            $mallGoods = $this->model_mall->getGoodsAttire($userId);
            $userData['attires'] = $mallGoods;

            //用户铭牌
            $userData['userNameplate'] = $this->nameplateModel->getNameplateByUserId($userData['user_id']);
        }
        //登录用户
        if(!empty($loginUserId)) {
            $userAgent = $this->userAgentModel->getUserAgent($loginUserId);
            $userData['login_user_info']['agent']['status'] = empty($userAgent['status']) ? 0 : $userAgent['status'];
            $userData['login_user_info']['agent']['rate'] = empty($userAgent['rate']) ? 0 : $userAgent['rate'];
            $userData['login_user_info']['agent']['hasPass'] = empty($userAgent['password']) ? 0 : 1;
        }

        return $userData;
    }

    // 修改游客手机号
    public function modifyVisitorPhone($userId, $phone)
    {
        return $this->user->modifyVisitorPhone($userId, $phone);
    }

    //生成详情返回数据
    public function getDetailResponseData($userId, &$cur_user_id){
        //$userData = $this->user->getUserInfo(['user_id'=>$userId],$fields);
        $userData = $this->user->get_user($userId);
        $parseAppUa = $this->parse_app_UA();
        $channelId = $parseAppUa['channel_id'] ?? 0;
        // 拼接个性标签
        $tags = $this->getUserTagsList();
        $meUserTagsMap = array_column($tags['me'], 'name', 'tag_id');
        $otherUserTagsMap = array_column($tags['other'], 'name', 'tag_id');
        $meUserTagsTemp = $userData['tags'];
        $userData['tags'] = [];
        $userData['tagsV2'] = [];
        $otherUserTagsTemp = $userData['other_tags'];
        $userData['other_tags'] = [];
        foreach($meUserTagsTemp as $u) {
            if(!isset($meUserTagsMap[$u])) {
                continue;
            }
            $userData['tags'][] = $meUserTagsMap[$u];
            $userData['tagsV2'][] = ['tag_id'=>$u,'name'=>$meUserTagsMap[$u]];
        }

        foreach($otherUserTagsTemp as $u) {
            if(!isset($otherUserTagsMap[$u])) {
                continue;
            }
            $userData['other_tags'][] = $otherUserTagsMap[$u];
        }

        $is_forbid = $this->user->is_forbid($userId);
        if ($is_forbid){
            $responseData['forbid'] = $is_forbid;
            if ($is_forbid == 2) {
                $userData = [
                    'user_id' => $userId,
                    'nickname' => "该用户永久封禁",
                    'images' => User::USER_DEFAULT_IMAGE,
                    'thumbnails' => User::USER_DEFAULT_IMAGE
                ];
            }
        }else{
            $responseData['forbid'] = 0;
        }

        if(!empty($userData)){
            $wallet = $this->userWallet->get_wallet($userData['user_id']);
            if(!empty($wallet)){
                $userData['diamond_balance'] = $wallet['diamond_balance'];
                $userData['charm_balance'] = $wallet['charm_balance'];
                $userData['wealth_balance'] = $wallet['wealth_balance'];
                $userData['pearl_balance'] = $wallet['pearl_balance'];
                $userData['reputation_balance'] = $wallet['reputation_balance'];
                $userData['celebrity_balance'] = $wallet['celebrity_balance'];
                $userData['hc_balance'] = $wallet['hc_balance'];
                $userData['jd_balance'] = $wallet['jd_balance'];
//                $userData['game_balance'] = $wallet['game_balance'];
                $userData['game_balance'] = empty($wallet['game_balance']) ? 1 : $wallet['game_balance'];
                $userData['agent_jd_balance'] = $wallet['agent_jd_balance'];
                $userData['debris_balance'] = $wallet['debris_balance'];
            }
            $userData['fans_count'] = $this->model_friends->get_fans_count($userId);
            $userData['follow_count'] = $this->model_friends->get_follows_count($userId);

        }
        $attires = $this->model_mall->getGoodsAttire($userId);
        $responseData['attires'] = $attires;
        $userData['profile_percent'] = (new UserProfileServices())->getCompletion($userId);//用户资料完成度
        $cur_user = $this->user->get_current_user();
        $userData['cool_number_expiry_time'] = (new ShoppingMallOrderServices())->getCoolNumberExpiryTime($userId);// 靓号过期时间(Unix时间戳)
        if ($cur_user && $cur_user['user_id'] != $userId) {// 非用户本人，不显示靓号到期时间
            $userData['cool_number_expiry_time'] = 0;
        }

        //用户头像审核状态
        $oldVerify = array_fill(0,count($userData['images']),1);
        $newVerify = [];
        //用户自己
        if ($cur_user && $cur_user['user_id'] == $userId) {
            // 用户本人，显示未审核的头像
            $checkImages = $this->getContentCheckAvatar($userId, $userData['images']);
            $userData['adapt_images'] = array_merge($userData['adapt_images'], $checkImages);
            $userData['images'] = array_merge($userData['images'], $checkImages);
            $userData['thumbnails'] = array_merge($userData['thumbnails'], $checkImages);
            $newVerify = array_fill(count($userData['images']),count($checkImages),0);
        }
        $userData['image_verify'] = array_merge($oldVerify,$newVerify);
        //去除重复值
        $userData['images'] = array_unique($userData['images'] );
        $userData['adapt_images'] = array_unique($userData['adapt_images'] );
        $userData['thumbnails'] = array_unique($userData['thumbnails'] );
        $responseData['user'] = $userData;

        //用户预设头像信息
        $prepareImg = Redis::get($this->prepare_img_key.$userId);
        $responseData['user']['prepare_img'] = empty($prepareImg) ? '' : $prepareImg;

        //进场特效
        $responseData['user_rides'] = $this->model_mall->getUserGoodsList($userId,2);

        $responseData['follow_list'] = [];  //兼容旧版本 估计2019.5月久能彻底干掉了
        //用户管理员所在房间
        $role_rooms = $this->room->get_role_rooms($userId);
        foreach ($role_rooms as $k => $v){
            $role_rooms[$k]['is_hostmicro'] = false;
            $cur_room_id = $this->model_roomuser->get_user_cur_room($userId);
            if (!empty($cur_room_id)){
                if ($this->model_roomhostmicro->get_user_id($cur_room_id) == $userId){
                    $role_rooms[$k]['is_hostmicro'] = true;
                }
            }
            $role_rooms[$k]['opened'] = $this->room->get_opened($v['room_id']);

            $role = $this->room->get_role($v['room_id'], $cur_user['user_id']);
            $role_rooms[$k]['allow_open'] = false;
            if ($role != 0){
                $role_rooms[$k]['allow_open'] = true;
            }
            if ($role_rooms[$k]['business_type'] == 1 && $role_rooms[$k]['certified'] == 0){
                unset($role_rooms[$k]);
            }
            if (!$role_rooms[$k]['opened']) {
                unset($role_rooms[$k]);
            }
        }
        $responseData['room_list'] = array_values($role_rooms);

        //是否关注 & 是否屏蔽
        $responseData['is_follow'] = $this->model_friends->get_follow_exist($cur_user['user_id'], $userId);
        $responseData['is_block'] = $this->model_friends->get_block_exist($cur_user['user_id'], $userId);
        $responseData['follow_status'] = $this->model_friends->is_friends($cur_user['user_id'], $userId);

        //添加浏览
        if ($cur_user != null){
            if (empty($cur_user['super'])){
                //查询是否使用隐藏足迹道具（道具清除卡）
                $propUseInfo = $this->userPropModel->getPropUseTime($cur_user['user_id'], 16, $userId);
                if (!$propUseInfo && $userId && intval($userId) != 0) {
                    $this->model_friends->add_browse($cur_user['user_id'], $userId);
                }
            }
            $cur_user_id = $cur_user['user_id'];
        }

        $responseData['is_sign_union'] = 0;
        $responseData['sign_union'] = '';

        //获取礼物墙数量开关
        $responseData['gift_status'] = $this->user->getGiftSwitch($userId);
        $responseData['user']['remark_name'] = !empty($cur_user_id) ? $this->user->getUserRemark($cur_user_id ,$userId) : '';

        //心情
        $responseData['user']['mood_name'] = '';
        $responseData['user']['mood_image'] = '';

        //获取用户正在使用的装备
        $responseData['userEquip'] = $this->equipModel->getUserEquipByUserId($userId);

        //用户铭牌
        $responseData['user']['userNameplate'] = $this->nameplateModel->getNameplateByUserId($userId);

        //用户是否在房间锁麦
        $responseData['user']['micro_lock'] = (object) $this->roomMicroModel->getRoomLockMicroByUserId($userId);
        if(!empty($responseData['user']['micro_lock']->room_id)) {
            $roomInfo = $this->room->get_room($responseData['user']['micro_lock']->room_id);
            $responseData['user']['micro_lock']->room_name = empty($roomInfo['name']) ? '' : $roomInfo['name'];
        }

        return $responseData;
    }

    /**
     * 通过手机号设置密码
     * @param $phone
     * @param $password
     * @return bool
     */
    public function setUserPassword($phone,$password){
        $user = $this->user->get_user_by_phone($phone);
        if ($user == null){
            return false;
        }
        $this->user->set_password($user['user_id'], $this->makeHashPassword($password));
       //return $this->user->updateUser(['mobile_phone'=>$phone],['password'=>$this->makeHashPassword($password)]);

    }
    public function setUserPasswordWToken($new_password){
        //$token = getTokenFCookie();
        $user = $this->user->get_current_user();
        if ($user == null){
            return false;
        }
        return $this->user->set_password($user['user_id'], $this->makeHashPassword($new_password));
    }

    public function getUserData($userId, $self = false)
    {
        return $this->user->get_user($userId, $self);
    }

    //用户手机号密码登录
    public function local_login($type, $data, &$user_id = null, $cancel = null, $checkPass = true){
        $uaData = $this->parse_app_UA();
        //设备封禁状态
        $deviceForbid = $this->user->get_forbid_device($uaData['guid']);
        if($deviceForbid == 1)
        {
            return Hint::DEVICE_FORBID;
        }
        $condition['mobile_phone'] = $data['phone'];
        //$userData = $this->user->getUserInfo($condition,['user_id','password']);
        $userData = $this->user->get_password_by_phone($data['phone']);
        $user_id = $userData['user_id'];

        if(empty($userData)){
            return Hint::USER_IS_NOT_EXIST;
        }else{
            //登录设备>5封号
            $device=$this->model_user_login_log->getDeviceNumByUserId2($user_id);
            if($device>5){
                $timeout=0;
                $this->user->set_forbid_user($user_id,$timeout);
            }
            //账号密码登录
            if($type == 1){

                if($checkPass && $userData['password'] != $this->makeHashPassword($data['password'])) {
                    return Hint::PASSWORD_ERROR;
                }
            }

            //账号验证码登录
            if($type == 2){

            }

            //设置登录
            //$login_res = $this->refreshUserToken($userData['user_id']);
            $login_res = $this->user->set_current_user($userData['user_id']);
            if($login_res){
                $responseData = $this->getResponseData($userData['user_id']);
                $responseData['rong_token'] = $this->get_rong_token($responseData);
                $responseData['user_token'] = $this->user->getUserToken();
                
                //更新账号异常登录忽略
                $is_forbid = $this->user->is_forbid($userData['user_id']);
                if ($is_forbid){
                    return Hint::USER_FORBID;
                }

                //账号注销撤回处理
                if ($cancel !== null && intval($cancel) === 0) {
                    $this->user->removeAccountCancel($userData['user_id']);
                } else {
                    //查询账号是否注销
                    if ($this->user->getAccountCancel($userData['user_id'])){
                        return Hint::USER_ACCOUNT_IS_CANCEL;
                    }
                }
                $this->UserAccountCancelModel->updateCancelLog($user_id);

                return $responseData;

            }else{
                return Hint::ERROR;

            }
        }

    }

    /**
     * wap页面登录功能
     * @param $phone
     * @param $password
     * @return mixed|null
     */
    public function mp_login($phone, $password){
        $userData = $this->user->get_password_by_phone($phone);
        $password = $this->makeHashPassword($password);
        if ($userData['password'] == $password){
            if ($this->user->is_forbid($userData['user_id'])){
                return null;
            }
            $responseData = $this->getResponseData($userData['user_id']);
            $_SESSION['user_id'] = $userData['user_id'];
            return $responseData;
        } else{
            return null;
        }
    }


    /**
     * wap 获取登录用户信息
     * @return mixed|null
     */
    public function mp_info(){
        if (!isset($_SESSION['user_id'])){
            return null;
        }
        return $this->getResponseData($_SESSION['user_id']);
    }

    //绑定手机号
    public function bindPhoneService($phone){
        $user = $this->user->get_current_user();
        if ($user == null){
            return false;
        }
        return $this->user->set_phone($user['user_id'], $phone);
        //return $this->user->updateUser(['token'=>$token],['mobile_phone'=>$phone]);
    }

    //编辑资料
    public function editUserData(
        $home, $nickname, $gender, $birthday, $images, $affective_state,
        $occupation, $school, $sign, $voice, $voice_time = 0, $inviteUserId = 0 ,
        $vest_switch = -1, $height = 0, $mood_id=0, $identity_role=0, $chat_sign='', $inviteUserIdNew = 0)
    {
        $user = $this->user->get_current_user();
        $this->user->chat_friend_base_info($images, $user['user_id'], $voice, $sign, $user, $chat_sign);
        //修改头像时，头像需要审核，所以这里不新增头像，但是有删除的需要删除
        $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
        if ($contentCheckSwitch) {
            $newImages = explode(',', $images);
            $addImage = diffPortrait($newImages,$user['images']);
            $delImage = diffPortrait($user['images'], $newImages);

            //去掉新增的图片，因为未审核
            if(!empty($newImages)) {
                if (!empty($addImage)) {
                    foreach ($newImages as $key => $img) {
                        if (strpos($img, 'portrait/') !== false) {
                            continue; //系统头像不过滤
                        }
                        foreach ($addImage as $s) {
                            if (strpos($img, $s) !== false) {
                                unset($newImages[$key]);
                            }
                        }
                    }
                }
                //去掉已删除的图片，因为已删除
                if (!empty($delImage)) {
                    foreach ($newImages as $key => $img) {
                        foreach ($delImage as $s) {
                            if (strpos($img, $s) !== false) {
                                unset($newImages[$key]);
                            }
                        }
                    }
                }

                //如果没有头像，则设置一张默认头像
                if(empty($newImages)){
                    $newImages = User::USER_DEFAULT_IMAGE;
                }
                $images = implode(',', array_merge($newImages));
            }
        }

        //已经填写过了邀请用户就不应更新
        if(!empty($user['invite_uid'])) {
            $inviteUserId = 0;
        }

        //注册是绑定邀请用户了就不再更新
        if(!empty($user['invite_uid_new'])) {
            $inviteUserIdNew = 0;
        }

        write_log('user-invite', 'editUserData', ['user_id' => $user['user_id'], 'inviteUserIdNew' => $inviteUserIdNew]);

        $ret = $this->user->edit($user['user_id'], $home, $nickname, $gender, $birthday,
        $images, $affective_state, $occupation, $school, $sign, $voice, $voice_time,
        $inviteUserId,$vest_switch, $height, $mood_id, $identity_role, 0, $inviteUserIdNew);

        if($ret && !empty($inviteUserId)) {
            //埋点
            $this->tdService->handleTrack('invite', ['user_id'=>$inviteUserId, 'invite_user'=>$user['user_id']]);

            //用户邀请关系确定
            $publishObject = Publisher::getInstance();
            $publishObject->requestData = [
                'queue_route' => 'global.user.invite',
                'data' => [
                    'mqtype' => 2,
                    'user_id' => $user['user_id'],
                ],
            ];
            $publishObject->publisher();
        }

        $room = $this->room->get_room_by_userid($user['user_id']);
        if (empty($room)) {
            return $ret;
        }
        if (empty($room['name']) && !empty($user['nickname'])) {
            $this->room->set_name($room['room_id'], $user['nickname'] . '的房间');
            //内容检测开关
            $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
            if ($contentCheckSwitch) {
                $this->contentCheckModel->create($user['user_id'], 3, $user['nickname'] . '的房间', "聊天室", $room['room_id']);
            }
        }
        if (empty($room['image']) && !empty($user['images'])){
            $this->room->set_image($room['room_id'], $user['images'][0]);
            //内容检测开关
            $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
            if ($contentCheckSwitch) {
                $this->contentCheckModel->create($user['user_id'], 7, $user['images'][0], "", $room['room_id']);
            }

        }
        return $ret;
    }

    public function setEditUser($user_id,$nickname,$images,$gender){
        return $this->user->edit($user_id, '', $nickname, $gender, '', $images, '', '', '', '');
    }

    public function setUserBaseInfo($user_id, $nickname, $gender, $birthday, $images)
    {
        return $this->user->edit($user_id, '', $nickname, $gender, $birthday, $images, '', '', '', '');
    }

    //昵称校验
    public function nickCheck($nickname){
        //$token = getTokenFCookie();
        $user = $this->user->get_current_user();
        $wallet = $this->userWallet->get_wallet($user['user_id']);
        if ($wallet['wealth_balance'] >= 8000000){
            return true;
        }
        return !$this->user->check_exist($nickname, $user['user_id']);
    }

    //校验密码 手机号/token
    public function passwordCheck($phone = '',$password)
    {
        $password = $this->makeHashPassword($password);
        $password_user = null;
        if($phone){
            //$res = $this->user->getSingle(['mobile_phone'=>$phone,'password'=>$password],['user_id']);
            $password_user = $this->user->get_password_by_phone($phone);
        }else{
            //$token = getTokenFCookie();
            $user = $this->user->get_current_user();
            $password_user = $this->user->get_password($user['user_id']);
            //$res = $this->user->getSingle(['token'=>$token,'password'=>$password],['user_id']);
        }
        if (empty($password_user)){
            return false;
        }
        if ($password_user['password'] == $password){
            return true;
        }

        return false;
    }

    //校验手机号状态
    public function phoneStatus($phone)
    {
        //1：未注册 2：已注册&当前登录账户  3：已注册&非当前登录账户 4:已注册&未登录
        $curr_user = $this->user->get_current_user();
        if ($curr_user != null && $curr_user['phone'] == $phone){
            return 2;
        }
        $phone_user = $this->user->get_user_by_phone($phone);
        if ($phone_user == null){
            return 1;
        }
        return 3;
    }

    /*
    //更新token
    private function refreshUserToken($userId){
        $token = getRoundToken();
        //$data = ['token'=>$token,'expire_time'=>time()+self::$expire];
        //$result = $this->user->updateUser(['user_id'=>$userId],$data);
        $result = $this->user->set_token($userId, $token, self::$expire);
        if($result !== false){
            $this->setLogin($token);
            return true;
        }else{
            return false;
        }
    }
    */

    //
    private function makeHashPassword($password){
        return md5($this->passwordHash.$password);
    }



    //账号绑定页面初始化
    public function accountInitService()
    {
        $ret = ['phone' => '', 'qq' => '','wechat' => '', 'weibo' => '', 'llwechat'=>'', 'llqq'=>''];
        $user = $this->user->get_current_user();
        if (empty($user)) {
            return false;
        }
        $userId = $user['user_id'];
        $thirdRet = $this->thirdUser->getThirdUser(['user_id' => $userId]);
        if (!empty($thirdRet)) {
            foreach ($thirdRet as $k => $v) {
                if ($v['source'] == 1) {
                    //$ret['qq'] = hide_string($v['openid']);
                    $ret['qq'] = $v['openid'];
                } elseif ($v['source'] == 2) {
                    //$ret['wechat'] = hide_string($v['openid']);
                    $ret['wechat'] = $v['openid'];
                } elseif ($v['source'] == 5) {
                    //$ret['wechat'] = hide_string($v['openid']);
                    $ret['llwechat'] = $v['openid'];
                } elseif ($v['source'] == 6) {
                    //$ret['wechat'] = hide_string($v['openid']);
                    $ret['llqq'] = $v['openid'];
                } elseif ($v['source'] == 7) {
                    //$ret['wechat'] = hide_string($v['openid']);
                    $ret['ttwechat'] = $v['openid'];
                } elseif ($v['source'] == 8) {
                    //$ret['wechat'] = hide_string($v['openid']);
                    $ret['hhwechat'] = $v['openid'];
                } else {
                    //$ret['weibo'] = hide_string($v['openid']);
                    $ret['weibo'] = $v['openid'];
                }
            }
        }
        //$ret['phone'] = hide_string($user['phone']);
        $ret['phone'] = $user['phone'];
        $ret['false_mobile'] = 0;
        $ret['allow_op'] = env('FALSE_MOBILE_ALLOW_OP', 1);
        $ret['all_op'] = env('FALSE_MOBILE_ALLOW_OP', 1);
        if (isset($ret['phone']) && substr($ret['phone'] , 0 , 1) == 2) {
            unset($ret['phone']);
            $ret['false_mobile'] = 1;
        }
        return $ret;
    }

    //第三方登录
    public function thirdLoginService($source, $platform, $accessToken,$refreshToken = '', $openId = '', $cancel = null, &$userId)
    {
        switch ($source) {
            case 1: //qq
                $thirdUserInfo = $this->thirdQq->run($accessToken);
                break;
            case 2://wechat
                $thirdUserInfo = $this->thirdWechat->run($accessToken, $refreshToken, $openId);
                break;
            case 9://苹果登录
                $thirdUserInfo = $this->thirdAppleJwtVerify->run($openId ,$accessToken);
                break;
            default:
                $thirdUserInfo = false;
                break;
        }

        if(!$thirdUserInfo){// 获取信息失败
            return $thirdUserInfo;
        }

        // 处理壳壳微信\来来微信\天天微信互通
        $sourceArr = [2, 5, 7, 8];
        if (in_array($source, $sourceArr)){

            $interflowCurThirdUser = $this->thirdUser->get_third($thirdUserInfo['openid'], $source);
            $tmpKey = array_search($source, $sourceArr);
            //unset($sourceArr[$tmpKey]);

            if (empty($interflowCurThirdUser)){
                foreach ($sourceArr as $otherSource){
                    $interflowOtherThirdUser = $this->thirdUser->getThirdByUnion($thirdUserInfo['unionid'], $otherSource);
                    if (!empty($interflowOtherThirdUser)){
                        $addData = [
                            'user_id'=>$interflowOtherThirdUser['user_id'],
                            'openid'=>$openId,
                            'unionid'=>$thirdUserInfo['unionid'],
                            'platform_type'=>$platform,
                            'source' => $source,
                            'portrait'=> $thirdUserInfo['portrait'],
                            'nickname' => $thirdUserInfo['nickname'],
                            'create_timestamp'=>time()
                        ];
                        $this->thirdUser->addThirdUser($addData);
                        break;
                    }
                }
            } else {
                //检查unionid是否变更，如果变更则更新数据
                if ($interflowCurThirdUser['unionid'] != $thirdUserInfo['unionid']) {
                    $this->thirdUser->setUnionId($thirdUserInfo['openid'], $source, $thirdUserInfo['unionid']);
                }

                //如果记录中没有user_id，则补充user_id
                if (empty($interflowCurThirdUser['user_id'])){
                    foreach ($sourceArr as $otherSource) {
                        $interflowOtherThirdUser = $this->thirdUser->getThirdByUnion($thirdUserInfo['unionid'], $otherSource);
                        if (!empty($interflowOtherThirdUser) && !empty($interflowOtherThirdUser['user_id'])) {
                            $this->thirdUser->setUserId($thirdUserInfo['openid'], $source, $interflowOtherThirdUser['user_id']);
                            break;
                        }
                    }
                }
            }

        }


        $checkRet = $this->thirdPartUserCheck($thirdUserInfo, $source, $platform);
        if ($checkRet['flag'] === false) {
            $oldUser = $this->getResponseData($checkRet['user_id'], true);
            $oldUser['openid'] = $checkRet['openid'];
            $userId = $checkRet['user_id'];
            if ($this->user->is_forbid($checkRet['user_id'])){
                return Hint::USER_FORBID;
            }
            //账号注销撤回处理
            if ($cancel !== null && intval($cancel) === 0) {
                $this->user->removeAccountCancel($checkRet['user_id']);
            } else {
                //查询账号是否注销
                if ($this->user->getAccountCancel($checkRet['user_id'])){
                    return Hint::USER_ACCOUNT_IS_CANCEL;
                }
            }
            $this->user->set_current_user($checkRet['user_id']);
            $this->UserAccountCancelModel->updateCancelLog($checkRet['user_id']);
            $oldUser['rong_token'] = $this->get_rong_token($oldUser);

            return $oldUser;
        } else {

            return null;
        }
    }

    //第三方账号绑定
    public function thirdPartBindService($actType, $source, $platform, $accessToken = '', $refreshToken = '', $openId = '')
    {
        $bindFlag = true;
        $thirdUserInfo = [];
        if($actType == 1){//绑定
            switch ($source) {
                case 1: //qq
                    $thirdUserInfo = $this->thirdQq->run($accessToken);
                    break;
                case 2://wechat
                    $thirdUserInfo = $this->thirdWechat->run($accessToken, $refreshToken, $openId);
                    break;
                case 3://weibo
                    $thirdUserInfo = $this->thirdWeibo->run($accessToken);
                    break;
                case 5://缘音wechat
                    $thirdUserInfo = $this->thirdLLWechat->run($accessToken, $refreshToken, $openId);
                    break;
                case 7://天天wechat
                    $thirdUserInfo = $this->thirdTTWechat->run($accessToken, $refreshToken, $openId);
                    break;
                case 8://火火wechat
                    $thirdUserInfo = $this->thirdHHWechat->run($accessToken, $refreshToken, $openId);
                    break;
                default:
                    $bindFlag = false;
                    break;
            }
            $this->thirdPartUserCheck($thirdUserInfo, $source, $platform);
        }


        if($thirdUserInfo === false){//获取信息失败
            $bindFlag = false;
        }

        if ($bindFlag === false) {
            return $bindFlag;
        }
        $checkRet = $this->thirdPartUserMove($actType, $thirdUserInfo, $source, $openId);
        return $checkRet;
    }

    //第三方账号操作绑定/解绑
    private function thirdPartUserMove($actType, array $thirdUserInfo, $source, $openId = '')
    {
        $user = $this->user->get_current_user();
        if (empty($user)) {
            return false;
        }
        $userId = $user['user_id'];

        if ($actType == 1) {
            $condition = ['openid' => $thirdUserInfo['openid'], 'source' => $source];
            $bindRet = $this->thirdUser->updateThirdUser($condition, ['user_id' => $userId]);
        } else {
            //未绑定手机号不允许解绑
            if(empty($user['phone']) || substr($user['phone'] ,0,1) != 1){
                return Hint::USER_ACCOUNT_MOBILE_NOT_BIND;
            }
            $condition = ['user_id' => $userId, 'source' => $source];
            $bindRet = $this->thirdUser->updateThirdUser($condition, ['user_id' => 0]);
        }
        if ($bindRet === false) {
            return false;
        }
        return true;
    }

    //第三方登录校验用户&增加未绑定用户
    private function thirdPartUserCheck(array $thirdUserInfo, $source, $platform)
    {
        $checkReturn = ['flag'=>true];
        $openId = $thirdUserInfo['openid'];
        $checkRet = $this->thirdUser->checkThirdUser(['openid' => $openId, 'source' => $source], ['user_id','openid']);

        $time = time();
        if (empty($checkRet)) {
            $addData = ['openid'=>$openId,'unionid'=>$thirdUserInfo['unionid'],'platform_type'=>$platform, 'source' => $source, 'portrait'=> $thirdUserInfo['portrait'], 'nickname' => $thirdUserInfo['nickname'], 'create_timestamp'=>$time];
            $this->thirdUser->addThirdUser($addData);
        } else {
            if($checkRet['user_id'] != 0){
                $checkReturn['flag'] = false;//老用户
                $checkReturn['user_id'] = $checkRet['user_id'];
                $checkReturn['openid'] = $checkRet['openid'];
            }
        }

        return $checkReturn;
    }

    //第三方登录绑定用户
    private function thirdUserBindMethod($openid, $source, $userId)
    {
        $bindRet = $this->thirdUser->updateThirdUser(['openid' => $openid, 'source' => $source], ['user_id' => $userId]);
        $third = $this->thirdUser->get_third($openid, $source);
        $user = $this->user->get_user($userId, true);
        if (!empty($user) && !empty($third)){
            $nickname = null;
            $portrait = null;
            if (empty($user['nickname'])){
                $nickname = '甜枕用户'.$user['user_uid'];
            }
            if (empty($user['portrait'])){
                $portrait = "album/default.png";
            }
            if (!empty($nickname) || !empty($portrait)){
                $this->user->edit($user['user_id'], null, $nickname, null, null, $portrait, null, null, null, null);
                /*$room = $this->room->get_room_by_userid($user['user_id']);
                if (empty($room['name']) && !empty($nickname)) {
                    $this->room->set_name($room['room_id'], $nickname . '的房间');
                }
                if (empty($room['image']) && !empty($portrait)){
                    $images = explode(',', $portrait);
                    $this->room->set_image($room['room_id'], $images[0]);
                }
                此处不设置房间
                */

            }

        }
        if($bindRet === false){
            return false;
        }
        return true;
    }

    //第三方登录绑定or新增用户
    public function thirdUserBind($phone, $openid, $source, $inviteUserId = 0)
    {
        $bindFlag = false;
        //$checkRet = $this->user->getUserInfo(['mobile_phone' => $phone], ['user_id']);
        $checkRet = $this->user->get_user_by_phone($phone);
        $checkThirdRet = $this->thirdUser->checkThirdUser(['openid' => $openid, 'source' => $source], ['user_id']);

        if (!empty($checkRet)) {
            $userId = $checkRet['user_id'];
            if(!empty($checkThirdRet)){
                $bindRet = $this->thirdUserBindMethod($openid, $source, $userId);
                if($bindRet !== false){//绑定成功
                    //$this->refreshUserToken($userId);
                    $this->user->set_current_user($userId);
                    $bindFlag = $this->getResponseData($userId);
                    $bindFlag['rong_token'] = $this->get_rong_token($bindFlag);
                }
            }

        } else {
            $userId = $this->createUserNPwdService($phone, $inviteUserId);
            if($userId){
                //$this->user->set_guid($userId, $guid);
                $this->createWalletService($userId);
                $userData = $this->user->get_user($userId);
                event(new RoomRegisterEvent($userData, 1));
                $bindRet = $this->thirdUserBindMethod($openid, $source, $userId);
                if($bindRet !== false){//绑定成功
                    //$this->refreshUserToken($userId);
                    $this->user->set_current_user($userId);
                    $bindFlag = $this->getResponseData($userId);
                    $bindFlag['rong_token'] = $this->get_rong_token($bindFlag);
                }
            }

        }
        return $bindFlag;
    }

    /**
     * 退出登录
     * @return bool
     */
    public function login_out(){
        return $this->user->del_current_user();
    }

    /**
     * 设置融云用户信息并获取token
     * @param $user 用户array
     * @return string
     */
    //old func
//    public function get_rong_token($user){
//        $image = 'https://kkaudio.oss-cn-beijing.aliyuncs.com/test/_2.9.png';
//        if (!empty($user['images'])){
//            $image = $user['images'][0];
//        }
//        if (empty($user['nickname'])){
//            $user['nickname'] = '新用户';
//        }
//        return $this->lib_rong->get_token($user['user_id'], $user['nickname'], $image);
//    }
    public function get_rong_token($user)
    {
        $image = User::USER_DEFAULT_IMAGE[0];
        if (!empty($user['images'])) {
            $image = $user['images'][0];
        }
        if (empty($user['nickname'])) {
            $user['nickname'] = '新用户';
        }

        $token = $this->lib_rong->get_token($user['user_id'], $user['nickname'], $image ,$user['user_uid']);
        //设置缓存
        $this->user->setUserRongToken($user['user_id'], $token);

        return $token;
    }

    // 获取用户token
    public function getUserToken()
    {
        return $this->user->getUserToken();
    }

    // 获取用户融云token
    public function getUserRongToken($userId)
    {
        $token = $this->user->getUserRongToken($userId);
        if(empty($token)) {
            $userInfo = $this->user->get_user($userId, true);
            if(empty($userInfo)) {
                return '';
            }
            $token = $this->get_rong_token($userInfo);
        }
        return $token;
    }

    public function get_current_user(){
        return $this->user->get_current_user();
    }
    public function get_current_user_id(){
        return $this->user->get_current_user_id();
    }
    public function get_current_user_cookie(){
        return $this->user->get_current_user_cookie();
    }
    public function get_user_by_phone($phone){
        return $this->user->get_user_by_phone($phone);
    }
    public function search($key_word){
        return $this->user->search($key_word);
    }

    public function set_forbid_user($user_id, $timeout, &$room_id){
        $this->user->set_forbid_user($user_id, $timeout);
        $room_id = $this->model_roomuser->get_user_cur_room($user_id);
    }

    //获取用户封禁状态
    public function get_user_forbid_status()
    {
        $userId = $this->requestData['user_id'];
        $res = $this->user->is_forbid($userId);
        return $res == false ? 1 : 2;
    }

    public function set_forbid_device()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('guid', '手机唯一标识', 'string', true, 'guid不能为空');
                $this->I('type', '操作类型', 'int', true, '操作类型不能为空');// 1:封号 2:解封
                $this->I('reason_img', '凭证文件', 'string', false, '凭证文件不能为空');
                $this->I('operate_info', '操作说明', 'string', false, '操作说明不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                // 用户封号表
                $this->user->table = 'device_ban_log';
                $data['id'] = $this->user->insertSingle($this->requestData);
                if ($data['id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '设备封禁' . Hint::getErrCodeMsg($code);
                    break;
                }

                //todo setRedis
                if($this->requestData['type'] == 1){
                    $this->user->set_forbid_device($this->requestData['guid']);
                }else{
                    $this->user->del_forbid_device($this->requestData['guid']);
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取设备封禁状态
     * @param $guid
     */
    public function get_forbid_device()
    {
        $guid = $this->requestData['guid'];
        return $this->user->get_forbid_device($guid);
    }

    public function resetDevice()
    {
        $userId = $this->requestData['user_id'];
        return $this->user->resetDevice($userId);
    }

    public function remove_forbid_user($user_id){
        $this->user->remove_forbid_user($user_id);
    }


    public function get_forbid_list(){
        $list = $this->user->get_forbid_list();
        return $list;
    }


    /**
     * 设置靓号
     * @param $userId
     * @param $liang 0.非靓号、1.靓号
     */
    public function setLiang($userId, $liang){
        $this->user->setLiang($userId, $liang);
    }


    /**
     * 设置超级管理
     * @param $userId
     * @param $super 0.非超管、1.超管
     */
    public function setSuper($userId, $super){
        $this->user->setSuper($userId, $super);
    }


    /**
     * 设置官方
     * @param $userId
     * @param $official 0.非官方、1.官方
     */
    public function setOfficial($userId, $official){
        $this->user->setOfficial($userId, $official);
    }


    /**
     * 设置接待(巡房)
     * @param $userId
     * @param $waiter 0.非接待、1.接待
     */
    public function setWaiter($userId, $waiter){
        $this->user->setWaiter($userId, $waiter);
    }


    /**
     * 设置加V
     * @param $userId int
     * @param $v int 0.取消加V、1.设置加V
     * @param $vDesc string 加V描述
     * @param $startTime int 加V生效时间
     * @param $endTime int 加V失效时间
     */
    public function setV($userId, $v, $vDesc, $startTime, $endTime){

        $params = [
            'v_start_time' => $v == 0 ? 0 : $startTime,
            'v_end_time' => $v == 0 ? 0 : $endTime,
        ];
        $this->user->editUserSet($userId, $params);

        $this->user->setV($userId, $v, $vDesc);
    }


    /**
     * 设置UID
     * @param $userId
     * @param $uid
     */
    public function setUid($userId, int $uid){
//        if ($uid >= 100000 && !filterUUID($uid)){
//            return Hint::USER_UID_NOT_LIANG; //非靓号不允许设置
//        }
        $old = $this->user->get_user_by_uid($uid);
        if (!empty($old)){
            return Hint::USER_UID_IS_EXIST; //已存在号码不能设置
        }
        $user = $this->user->get_user($userId);
        if (empty($user)){
            return Hint::USER_IS_NOT_EXIST; //用户不存在
        }
        $this->user->setUid($userId, $uid);
        $room = $this->room->get_room_by_userid($userId);
        if ($room) {
            $this->room->setUid($room['room_id'], $uid);
        }
    }


    /**
     * 用户注册日志
     * @param $user_id
     */
    public function user_register_log($user_id){

        // 避免重复注册
        if($this->model_user_register_log->getUserRegisterLog($user_id)) return [];

        $data = $this->parse_app_UA();
        $guid = $data['guid'];
        $platform = $data['channel_id'];

        $device = $this->modelDevice->get(['guid'=>$guid], true);
        if (!empty($device) && !empty($device['platform'])){
            $platform = $device['platform'];
        }
        $callback = $device['callback'] ?? '';
        $aid = $device['aid'] ?? '';
        $cid = $device['cid'] ?? '';
        $advertiserId = $device['advertiser_id'] ?? '';

        // 苹果渠道推广
        if('3001' == $data['channel_id']){
            $appleReortInfo = (new System())->appleReortInfo($guid);
            if($appleReortInfo && isset($appleReortInfo->iad_org_id) && $appleReortInfo->iad_org_id == 3170040){
                $platform = 'asa_haoxin';
            }
        }

        //创建注册日志
        $this->model_user_register_log->createdRegisterLog($user_id, $data['version_no'], $data['channel_id'], $data['device'], $data['os_name'], $platform ,$guid ,$callback, $cid, $aid, $advertiserId);
        $ua = $this->parse_app_UA();
        $this->model_user_login_log->createdLoginLog($user_id, $data['version_no'], $data['channel_id'], $data['device'], $data['os_name'],  client_ip() ??'', $ua['guid']);
        $this->setOsVersion($user_id, $data['version_no']);
        //广告归因，上报注册
        $this->platformReportServices->reportRegister($guid, $user_id);

        //记录用户tdid
        $this->user->saveUserIdTdid($user_id, (empty($_SERVER['HTTP_TDID'])?'':$_SERVER['HTTP_TDID']));
        //埋点
        $this->tdService->handleTrack('login', ['user_id'=>$user_id, 'is_first'=>1]);

        return [];
    }
    /**
     * 读取用户注册日志
     * @param $user_id
     */
    public function get_user_register_log($user_id){
        $data = $this->parse_app_UA();
        $guid = $data['guid'];
        if(empty($guid)){
            $data = $this->user->getUserInfoByCondition(['user_id'=>$user_id],['guid']);
            if(empty($data) || $data['guid'] == '') {
                return [];
            }
            $guid = $data['guid'];
        }
        $imei = '';
        $oaid = '';
        $channel_id = '';
        if ($guid != 'd41d8cd98f00b204e9800998ecf8427e'){
            $device = $this->modelDevice->get(['guid'=>$guid], true);
            $imei = $device['imei'] ?? '';
            $oaid = $device['oaid'] ?? '';
            $channel_id = $device['channel_id'] ?? '';
        }
        return [
            'user_id' => $user_id,
            'imei' => $imei,
            'oaid' => $oaid,
            'channel_id' => $channel_id,
        ];
    }

    /**
     * 获取上报给广告商的数据，公共方法，可增加参数，不能删除参数
     * @param $user_id
     * @return array
     */
    public function getUserDeviceData($user_id): array
    {
        $data = $this->parse_app_UA();
        $guid = $data['guid'];
        if(empty($guid)){
            $data = $this->user->getUserInfoByCondition(['user_id'=>$user_id],['guid']);
            if(empty($data) || $data['guid'] == '') {
                return [];
            }
            $guid = $data['guid'];
        }
        $result = [
            'user_id' => $user_id,
            'imei' => '',
            'oaid' => '',
            'idfa' => '',
        ];

        if ($guid == 'd41d8cd98f00b204e9800998ecf8427e'){
            return $result;
        }
        $device = $this->modelDevice->get(['guid'=>$guid], true);
        $result['imei'] = $device['imei'] ?? '';
        $result['idfa'] = $device['idfa'] ?? '';
        $result['oaid'] = $device['oaid'] ?? '';

        return $result;
    }

    /**
     * 用户登录日志
     * @param $user_id
     * @param $deviceId         //数美设备指纹标识（反作弊检测需要用到）
     * @param $advertisingId    //数美广告计费的设备ID（反作弊检测需要用到）
     */
    public function user_login_log($user_id, $deviceId = '', $advertisingId = ''){
        $data = $this->parse_app_UA();
        $ip = client_ip() ??'';
        $ua = $this->parse_app_UA();

        $this->model_user_login_log->createdLoginLog($user_id, $data['version_no'], $data['channel_id'], $data['device'], $data['os_name'] ,$ip, $ua['guid']);
        $this->setOsVersion($user_id, $data['version_no']);

        //记录用户tdid
        $this->user->saveUserIdTdid($user_id, (empty($_SERVER['HTTP_TDID'])?'':$_SERVER['HTTP_TDID']));
        //埋点
        $this->tdService->handleTrack('login', ['user_id'=>$user_id, 'is_first'=>0]);
    }


    /**
     * 更新渠道和channel
     */
    public function update_channel_guid($user_id = null){
        $user = $this->user->get_current_user();
        $data = $this->parse_app_UA();
        if (empty($user) && !empty($user_id)){
            $user = $this->user->get_user($user_id);
        }
        $guid = empty($user['guid']) ? $data['guid'] : $user['guid'];
        //查询设备表是否存在guid的信息不存在时候必须创建一个
        $device = $this->modelDevice->get(['guid'=>$guid], true);
        if(empty($device))
        {
            //创建device表数据
            $params['guid'] = $guid;//设备唯一号
            $params['idfa'] = '';
            $params['version_no'] = empty($data['version_no']) ? '' : $data['version_no'];
            $params['os_name'] = empty($data['os_name']) ? '' : $data['os_name'];
            $params['device'] = empty($data['device']) ? '' : $data['device'];
            $params['channel_id'] = empty($data['channel_id']) ? '' : $data['channel_id'];
            $this->modelDevice->save($params);
        }
        if (empty($user)){
            return;
        }
        if(!empty($user['guid'])) {
            return;
        }
        
        if(!empty($data['guid']) && empty($user['guid'])) {
            $this->user->set_guid($user_id, $data['guid']);
        }
        
        /*
        $user_id = $user['user_id'];

        $data = $this->parse_app_UA();
        //9f89c84a559f573636a47ff8daed0d33 默认guid 不更新
        if(!empty($data['guid']) && $user['guid'] != $data['guid'] && $data['guid'] != '9f89c84a559f573636a47ff8daed0d33'){
            $this->user->set_guid($user_id, $data['guid']);
        }

        if (!empty($data['channel_id']) && empty($user['channel_id'])){
            if ($data['channel_id'] == 1){
                $this->user->set_channel_id($user_id, 101);
            }else{
                $this->user->set_channel_id($user_id, $data['channel_id']);
            }
            return;
        }

        if (!empty($data['channel_id']) && $user['channel_id'] != $data['channel_id'] && $data['channel_id'] > 100000){
            $this->user->set_channel_id($user_id, $data['channel_id']);
        }
        */
    }

    /**
     * 通过用户UID（或user_id）获取用户信息
     *
     * @param uuid 用户生成的UUID
     * @param default 默认 true:用户生成的UUID false:用户自增user_id
     * */
    public function getUserInfoByUuid($uuid,$default = true)
    {
        $rest = $this->user->get_user_by_uid($uuid,$default);
        if (empty($rest)) {
            $rest = [];
        }
        $newData['user_id'] = $rest['user_id'];
        $newData['user_uid'] = $rest['user_uid'];
        $newData['nickname'] = $rest['nickname'];
        $newData['images'] = isset($rest['images'][0]) ? $rest['images'][0] : '';
    
        return $newData;
    }

    /**
     * 通过用户手机号获取用户信息
     * */
    public function getUserInfoByPhone($phone)
    {
        $rest = $this->user->get_user_by_phone($phone);
        if (empty($rest)) {
            $rest = [];
        }

        return $rest;
    }


    /**
     * 通过邀请ID获得用户
     * @param $code
     * @return array|mixed|null
     */
    public function getUserInfoByCode($code)
    {
	if (empty($code)) {
            return [];
        }

	$rest = $this->user->getUserByCode($code);
        if (empty($rest)) {
            $rest = [];
        }

        return $rest;
    }


    /**
     * cms 认证港澳台
     * @param int $user_id
     * @param int $active_certify
     * @return bool
     */
    public function cms_set_certify(int $user_id, int $active_certify = 1){
        return $this->user->set_certify($user_id, $active_certify);
    }


    /**
     * 获取封号列表
     * @return mixed
     */
    public function getForbidUsers(){
        $data = $this->user->get_forbid_list();
        $userIdArr = array_keys($data);
        $users = $this->user->get_users_by_ids(array_slice($userIdArr, 0, 50));
        $now = time();
        foreach ($users as $k => $v){
            $forbidTime = intval($data[$v['user_id']]);
            if ($forbidTime < $now and $forbidTime != 0){
                unset($users[$k]);
                continue;
            }
            $users[$k]['forbid_time'] = $forbidTime;
        }
        return array_values($users);
    }

    /**
     * 关键字搜索 用户/房间
     * */
    public function keywordsSearch()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('keywords', '关键词', 'string', true, '关键词不能为空');
            $this->I('type', '搜索类型', 'int', true, '搜索类型不能为空');// 0=搜索全部（用户、小屋/CBD房间），1=用户，2=小屋，3=CBD
            $this->I('page', '页数', 'int', false);
            $this->I('limit', '条数', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据

            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

//            $user = $this->user->get_current_user();
//            if(empty($user)){
//                $code = Hint::LOGIN_OUT;
//                $msg = Hint::getErrCodeMsg($code);
//                break;
//            }

            // 默认0页30条
            $page = $this->requestData['page'] ?? 0;
            $limit = $this->requestData['limit'] ?? 30;
            $keywords = (string) $this->requestData['keywords'];
            $keywords = mb_substr($keywords, 0, 30);
            $searchRes = [];

            switch ($this->requestData['type']){
                case 0:
                    // 查询所有 默认0页4条
                    $page = $this->requestData['page'] ?? 0;
                    $limit = $this->requestData['limit'] ?? 4;
                    $data['user'] = $this->user->keywordsSearch($keywords, $page,$limit);
                    $data['room_hut'] = $this->room->keywordsSearch($keywords, 0,$page,$limit);
                    $data['room_cbd'] = $this->room->keywordsSearch($keywords, 1,$page,$limit);
                    $data['room_cbd'] = $this->roomSearchFilter($data['room_cbd'], $user['user_uid']);
                    break;
                case 1:
                    $this->userBlacklistService->addUserSearchBlacklist($user, $keywords);
                    $data['user'] = $this->user->keywordsSearch($keywords, $page,$limit);
                    break;
                case 2:

                    $searchRes = $data['room_hut'] = $this->room->keywordsSearch($keywords, 0,$page,$limit);
                    break;
                case 3:
                    $searchRes = $data['room_cbd'] = $this->room->keywordsSearch($keywords, 1,$page,$limit);
                    $searchRes = $this->roomSearchFilter($searchRes, $user['user_uid']);
                    break;
                case 4:
                    $data['union'] = $this->modelUnion->searchUnion($keywords, $page, $limit);
                    break;
                default:
                    break;
            }

            // todo 安卓定义为数组,数据库存的是字符串,此处统一处理为数组
            if(isset($data['user'])) {
                foreach($data['user']['list'] as &$item) {
                    if(isset($item['tags']) && $item['tags']) {
                        $item['tags'] = json_decode($item['tags'], true);
                    } else {
                        $item['tags'] = [];
                    }

                    if(isset($item['other_tags']) && $item['other_tags']) {
                        $item['other_tags'] = json_decode($item['other_tags'], true);
                    } else {
                        $item['other_tags'] = [];
                    }
                }
                unset($item);
            }

            if($searchRes) {
                try{
                    $roomIdArr = array_column($searchRes['list'],'room_id');
                    $curUser = $this->user->get_current_user();
                    $this->searchRecords($roomIdArr, $curUser['user_id'] ?? 0);
                }catch(Exception $e) {
                    Log::debug('记录搜索用户', [ $e->getMessage() ]);
                }
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    ################# 后台调用 ##########################################

    /**
     * 用户封号创建
     * */
    public function blockCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');
                $this->I('uuid', '用户UID', 'int', true, '用户UID不能为空');
                $this->I('operation_id', '操作ID', 'int', true, '操作ID不能为空');// 后台操作用户ID
                $this->I('operate_type', '操作类型', 'int', true, '操作类型不能为空');// 0:解封 1:封号
                $this->I('block_time', '封号时长', 'int', true, '封号时长不能为空');// 秒
                $this->I('reason_id', '原因ID', 'int', true, '原因ID不能为空');// 二级分类
                $this->I('reason_img', '凭证文件', 'string', false, '凭证文件不能为空');
                $this->I('operate_info', '操作说明', 'string', false, '操作说明不能为空');
                $this->I('forbid_type', '屏蔽类型', 'int', true, '屏蔽类型不能为空');// 1:屏蔽用户 2:屏蔽设备
                $this->I('delete_trend', '删除动态类型', 'int', true, '删除动态类型不能为空');// 0:否 1:是  TODO 不参与数据库交互

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $deleteTrend = $this->requestData['delete_trend'];
                unset($this->requestData['delete_trend']);

                $this->requestData['operate_time'] = time();

                // 用户封号表
                $this->user->table = 'user_block_log';
                $data['id'] = $this->user->insertSingle($this->requestData);
                if ($data['id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '用户封号' . Hint::getErrCodeMsg($code);
                    break;
                }

                // 动态内容表 默认伪删除更改状态
                if($deleteTrend) {
                    $this->user->table = 'trends_content';
                    $this->user->singleUpdate(['user_id' => $this->requestData['user_id']], ['is_delete' => 1]);
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 用户封号更新
     * */
    public function blockUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '用户封号ID', 'int', true, '用户封号ID不能为空');
                $this->I('user_id', '用户ID', 'int', false, '用户ID不能为空');
                $this->I('uuid', '用户UID', 'int', false, '用户UID不能为空');
                $this->I('operation_id', '操作ID', 'int', false, '操作ID不能为空');// 后台操作用户ID
                $this->I('operate_type', '操作类型', 'int', false, '操作类型不能为空');// 0:解封 1:封号
                $this->I('block_time', '封号时长', 'int', false, '封号时长不能为空');// 秒
                $this->I('reason_id', '原因ID', 'int', false, '原因ID不能为空');// 二级分类
                $this->I('reason_img', '凭证文件', 'string', false, '凭证文件不能为空');
                $this->I('operate_info', '操作说明', 'string', false, '操作说明不能为空');
                $this->I('forbid_type', '屏蔽类型', 'int', false, '屏蔽类型不能为空');// 1:屏蔽用户 2:屏蔽设备

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $id = $this->requestData['id'];
                // 移除请求数据中的ID
                unset($this->requestData['id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                // 用户封号表
                $this->user->table = 'user_block_log';
                $ret = $this->user->singleUpdate(['id' => $id], $this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '用户封号' . Hint::getErrCodeMsg($code);
                    break;
                }

                $data['id'] = intval($id);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 用户封号删除
     * */
    public function blockRemove()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '用户封号ID', 'int', true, '用户封号ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                // 用户封号表
                $this->user->table = 'user_block_log';
                $ret = $this->user->singleRemove($this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '用户封号' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 用户信息编辑
     * */
    public function editUserInfo()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');
                $this->I('portrait', '相册链接', 'string', false, '用户相册不能为空');// json数据
                $this->I('sign', '用户签名', 'string', false, '用户签名不能为空');
                $this->I('is_open_code', '是否开启邀请码', 'int', false); // 0=不开启，1=开启

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $userId = $this->requestData['user_id'];
                // 移除请求数据中的ID
                unset($this->requestData['user_id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                // 更新
                $ret = $this->user->singleUpdate(['user_id' => $userId], $this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '用户信息' . Hint::getErrCodeMsg($code);
                    break;
                }
                // 清除cache
                $this->user->clear_cache($userId);

                // 查询用户信息数据
                $userInfoData = $this->user->get_user($userId, true);

                // 校验房间是否存在封面
                $roomData = $this->room->get_room_by_userid($userId);
                if (empty($roomData['image']) && !empty($userInfoData['images'])){
                    $this->room->set_image($roomData['room_id'], $userInfoData['images'][0]);
                }

                $data['user_id'] = $userId;

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 设置加V
     * @param $userId
     * @param $is_abnormal
     */
    public function setAbnormal($userId, $is_abnormal){
        $this->user->setAbnormal($userId, $is_abnormal);
    }


    /**
     * 获取封号时间
     * @param $userId
     * @return int
     */
    public function getForbidTime($userId){
        return $this->user->getForbidTime($userId);
    }

    /**
     * 用户账号注销申请
     * @return array
     */
    public function accountCancel(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('phone', 'phone', 'string', true, '手机号不能为空');
            $this->I('reg_time', 'reg_time', 'string', false, '注册时间');
            $this->I('address', 'address', 'string', false, '常用登录省市');
            $this->I('reg_type', 'reg_type', 'string', false, '注册方式');
            $this->I('reg_phone_type', 'reg_time', 'string', false, '常用登录手机型号');
            $this->I('pay_log', 'reg_time', 'string', false, '账号充值记录');
            $this->I('cash_log', 'reg_time', 'string', false, '账号提现记录');
            $this->I('msg', 'reg_time', 'string', false, '注销原因');
            $this->I('sms_code', 'reg_time', 'string', true, '短信验证码不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $phone = $this->requestData['phone'];
            if (!$phone || !FormatCheck::checkPhone($phone)) {
                $code = Hint::PHONE_FORMAT_ERR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $user = $this->user->get_current_user();
            if (empty($user)){
                $code = Hint::LOGIN_OUT;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $userId = $user['user_id'];

            if ($phone !== $user['phone']) {
                $code = Hint::USER_ACCOUNT_MOBILE_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            //校验验证码
            $sms_code = intval($this->requestData['sms_code']);
            $sms_cache_code = $this->user->getUserSmsCache($phone);
            if ($sms_code !== $sms_cache_code || strlen($sms_code) != 6){
                $code = Hint::SMS_CODE_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            //查询账号注销申请
            $accountCancel = $this->user->getAccountCancel($userId);
            if ($accountCancel) {
                $code = Hint::ERR_DATA_EXIST;
                $msg = "已申请" . Hint::getErrCodeMsg($code);
                break;
            }

            //添加账号注销申请 保留30天内数据
            $this->requestData['created_at'] = time();
            $ret = $this->user->setAccountCancel($userId, $this->requestData);
            if (!$ret) {
                $code = Hint::ERR_DATA_UPDATE_FAIL;
                $msg = '账号注销申请' . Hint::getErrCodeMsg($code);
                break;
            }

            //添加 注销 记录表
            $this->UserAccountCancelModel->createCancelLog(intval($userId), strval($phone));

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 用户隐身道具失效
     * @return array
     */
    public function propInvalid(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $user = $this->user->get_current_user();
            if (empty($user)){
                $code = Hint::LOGIN_OUT;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $userId = $user['user_id'];
            //设置隐身道具失效
            $result = $this->userPropModel->setPropInvalid($userId, 15);
            if (!$result) {
                $code = Hint::ERR_FAIL;
                $msg = "道具失效设置". Hint::getErrCodeMsg($code);
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }


    /**
     * 获取用户设置
     */
    public function getUserSet($userId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $data = $this->user->getUserSet($userId);
            $data['no_msg_friend_txt'] = "该功能仅限财富等级20级以上用户使用";
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 编辑用户设置
     * @return array
     */
    public function editUserSet($userId, $giftNotice, $noMsgFriend){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(!empty($giftNotice)) {
                $params['gift_notice'] = intval($giftNotice);
            }
            if(!empty($noMsgFriend)) {
                //判断用户财富值
                $userLevel = [];
                $wallet = $this->userWallet->get_wallet($userId);
                if ($wallet['wealth_balance'] < 100000){
                    $wealthRankList = $this->financeWealth->getWealthRankData();
                    foreach($wealthRankList as $val) {
                        //用户当前等级
                        if($val['min_value']<=$wallet['wealth_balance'] && $wallet['wealth_balance']<=$val['max_value']) {
                            $userLevel = $val;
                            break;
                        }
                    }

                    $code = Hint::WEALTH_NOT_ENOUGH;
                    $msg = "该功能仅限财富等级20级以上用户使用，您当前财富等级为".$userLevel['rank_name']."级，快去提升等级吧！";
                    break;
                }

                $params['no_msg_friend'] = intval($noMsgFriend);
            }
            $this->user->editUserSet($userId, $params);
        } while (false);

        return compact('code', 'msg', 'data');
    }


    /**
     * 获取手机号用户
     * @param $phone
     * @return mixed
     */
    public function getUserByPhone($phone){
        return $this->user->get_user_by_phone($phone);
    }

    /**
     * 处理注销用户
     */
    public function loopAccountCancel(){
        $time = time();
        $userDataArr = $this->user->getAllAccountCancel();
        $userIdArr = [];
        DB::beginTransaction();
        foreach ($userDataArr as $value){
            if ($time - $value['created_at'] > 30 * 24 * 3600){
                $userData = $this->user->get_user($value['user_id'], true);
                if (empty($userData)){
                    continue;
                }
                $this->user->addUserAccountCancel($userData['user_id'], $userData['phone'], $value['address'], $value['reg_type'], $value['reg_phone_type'], $value['msg']);
                $this->user->set_phone($userData['user_id'], strval(11100000000 + $userData['user_id']));
                $this->modelUserVerify->setResultEmpty($userData['user_id'] ,0 ,'注销');
                $userIdArr[] = $userData['user_id'];
            }
        }
        DB::commit();
        foreach ($userIdArr as $value){
            $this->user->removeAccountCancel($value);
        }
        return $userIdArr;
    }

    /**
     * 获取用户封号信息
     * @param $userId
     * @return Model|\Illuminate\Database\Query\Builder|mixed|null|object
     */
    public function getBlockInfo($userId){
        return $this->user->getBlockInfo($userId);
    }

    /**
     * 处理用户审核数据
     * @param $userId
     * @param $responseData 用户数据
     * @return array
     */
    public function userContentCheckHandle($userId, $responseData){


        $cur_user = $this->user->get_current_user();

        //查询审核相关数据是否存在
        $contentCheckList = $this->contentCheckModel->getContentCheckListByDataIdAndCheckObj($userId, [1,2,6,8]);
        foreach ($contentCheckList as $key => $value) {

            if ($cur_user && $cur_user['user_id'] == $userId) {
                if ($value['check_obj'] == 1) {
                    $responseData['nickname'] = $value['content'];
                }

                if ($value['check_obj'] == 2) {
                    $responseData['sign'] = $value['content'];
                }

                if ($value['check_obj'] == 6) {
                    $responseData['voice'] = $value['content'];
                    $voiceTimeContent = json_decode($value['content_add'], true);
                    $responseData['voice_time'] = $voiceTimeContent['voice_time'];
                }
            }

//            if ($value['check_obj'] == 8) {
//                //查询是否存在待审核照片
//                if ($cur_user['user_id'] != $userId) {
//                    $key = array_search($value['content'], $responseData['images']);
//                    if ($key !== false) {
//                        array_splice($responseData['images'], $key, 1);
//                        array_splice($responseData['thumbnails'], $key, 1);
//                    }
//
//                    if ($key === 0) {
//                        $responseData['images'][0] = User::USER_DEFAULT_IMAGE[0];
//                        $responseData['thumbnails'][0] = User::USER_DEFAULT_IMAGE[0];
//                    }
//                }
//            }
        }

//        if (empty($responseData['images'])) {
//            $responseData['images'] = User::USER_DEFAULT_IMAGE;
//            $responseData['thumbnails'] = User::USER_DEFAULT_IMAGE;
//        }

        return $responseData;
    }

    public function getFalseMobile()
    {
        return $this->user->getFalseMobile();
    }

    /**
     * 获取用户邀请列表
     * @return array
     */
    public function getUserInviteList(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        do {
            $userId = $this->requestData['user_id'];
            $data = $this->user->getUserInviteList($userId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //第三方 微信通过Code 获取 token
    public function getUserTokenService($source, $platform, $code)
    {
        switch ($source) {
            case 2://wechat
                $accessToken = $this->thirdWechat->getAccessTokenByCode($code);
                break;
            /*
            case 5://缘音wechat
                $accessToken = $this->thirdLLWechat->getAccessTokenByCode($code);
                break;
            case 7://天天wechat
                $accessToken = $this->thirdTTWechat->getAccessTokenByCode($code);
                break;
            case 8://火火语音wechat
                $accessToken = $this->thirdHHWechat->getAccessTokenByCode($code);
                break;
            */
            default:
                $accessToken = false;
                break;
        }

        return $accessToken;
    }

    /**
     * 获取用户邀请信息
     */
    public function getUserInviteInfo(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        do {
            $userId = $this->requestData['user_id'];
            $userInfo = $this->user->get_user($userId);
            if ($userInfo) {
                $data['nickname'] = $userInfo['nickname'];
                $data['user_id'] = $userInfo['user_id'];
                $data['images'] = $userInfo['images'];
                $data['thumbnails'] = $userInfo['thumbnails'];
            }
            // $data['code'] = "";
            // if ($userInfo['is_open_code'] == 1) {
                $data['code'] = $userInfo['code'];
            // }

            $config = $this->system_service->get_config();
            foreach ($config as $k => $v){
                $value = $v['value'];
                if ($v['type'] == 1){
                    $value = intval($v['value']);
                }
                $configMap[$k] = $value;
            }
            $share_invite_url = isset($configMap['share_invite_url']) ? $configMap['share_invite_url'] : '';
            $queryStr = '?';
            if (!empty($data['share_invite_url'])){
                $queryStr = parse_url($share_invite_url, PHP_URL_QUERY) ? '&' : '?';
            }

            $data['open_code']['is_open_code'] = isset($data['code']) ? 1 : 0;
            $data['open_code']['share']['title'] = isset($configMap['share_invite_title']) ? $configMap['share_invite_title'] : '';
            $data['open_code']['share']['msg'] = isset($configMap['share_invite_msg']) ? $configMap['share_invite_msg'] : '';
            $data['open_code']['share']['image'] = isset($configMap['share_invite_image']) ? build_image($configMap['share_invite_image']) : '';
            $data['open_code']['share']['url'] = $share_invite_url . $queryStr .'user_id='.$userId;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    # ------------------------------------------------------------------------------------------

    /**
     * 根据用户ID获取用户信息
     *
     * @param array $requestData 请求参数
     * @return array
     * */
    public function infoById($requestData)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');

            $checkParams = $this->check($requestData); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $getUser = $this->user->get_user($requestData['user_id']);
            if (empty($getUser)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '甜枕' . Hint::getErrCodeMsg($code);
                break;
            }

            $data = [
                'user_id' => $getUser['user_id'],
                'nickname' => $getUser['nickname'],
                'image' => $getUser['images'][0] ?? '',
                'gender' => $getUser['gender'],
            ];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 根据token获取用户信息
     *
     * @param array $requestData 请求参数
     * @return array
     * */
    public function infoByToken($requestData)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('token', 'token值', 'string', true, 'token不能为空');

            $checkParams = $this->check($requestData); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $userId = $this->user->get_cache_token_userid($requestData['token']);
            if (empty($userId)) {
                $code = Hint::TOKEN_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $getUser = $this->user->get_user($userId);
            if (empty($getUser)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '甜枕' . Hint::getErrCodeMsg($code);
                break;
            }

            $data = [
                'user_id' => $getUser['user_id'],
                'nickname' => $getUser['nickname'],
                'image' => $getUser['images'][0] ?? '',
                'gender' => $getUser['gender'],
            ];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**极光一键登录
     * @param $loginToken
     * @return array|mixed
     */
    public function jgLogin($loginToken){
        $appKey = $this->jgConfig['appKey'];
        $masterSecret = $this->jgConfig['masterSecret'];
        $res = $this->parse_app_UA();
        $from_app = $res['app'] ?? '';

        $headers = array();
        $headers[] = "Content-Type:application/json";
        $headers[] = "Authorization: Basic " . base64_encode($appKey.':'.$masterSecret);
        $params = array('loginToken'=>$loginToken);
        $res = curlRequest($this->jgConfig['apiHost'].'/v1/web/loginTokenVerify' ,$params ,'',$headers ,10,true);
        $phone = '';
        if(empty($res)){
            return  $phone;
        }
        $res = json_decode($res ,true);
        write_log('jiguang', 'jgLogin', $res);
        if($res['code'] ==8000){
            $phone = $this->jgPhoneDecrypt($res['phone'] ,$from_app);
            write_log('jiguang', 'phone', $phone);
        }
        return  $phone;
    }

    /**极光解密手机号
     * @param $phone
     * @return string
     */
    public function jgPhoneDecrypt($phone ,$app){
        $prefix = '-----BEGIN RSA PRIVATE KEY-----';
        $suffix = '-----END RSA PRIVATE KEY-----';
        $priKey = $this->jgConfig['priKey'];

        $result = '';
        $encrypted = $phone;
        $key = $prefix . "\n" . $priKey . "\n" . $suffix;
        openssl_private_decrypt(base64_decode($encrypted), $result, openssl_pkey_get_private($key));
        if($result){
            return $result;
        }
        return '';
    }

    public function shumeiVerfyCode($rid ,$ip ,$phone ,$deviceId){
        $url = "http://captcha.fengkongcloud.com/ca/v1/sverify";
        $params['accessKey'] = $this->smConfig['accessKey'];
        $params['data'] = array(
            'rid'=>$rid ,
            'ip'=>$ip,
            'tokenId'=>$this->user->generatedSmTokenId($phone),
            'deviceId'=> $deviceId
        );
        $res = curl_request($url ,$params ,'json','POST');
        if(empty($res)){
            return  Hint::ERR_FAIL;
        }
        $res = json_decode($res ,true);
        if($res['code'] ==1100 && $res['riskLevel'] == 'PASS'){
            return  Hint::SUCCESS;
        }
        return  Hint::ERR_FAIL;
    }

    /**校验本地是否存在风险数据
     * @param $deviceId
     * @param $phone
     * @return array
     */
    public function checkLocalIsExistRisk($deviceId ,$phone){
        $info = $this->user->getDeviceRisk($phone ,$deviceId);
        $res = [];
        if(!empty($info)){
            $res = array('score'=>$info->score ,'riskLevel'=>$info->risk_level);
        }
        return $res;
    }

    public function checkDeviceRisk($deviceId ,$phone, $ip){
        $header = $this->parse_app_UA();
        $url = "http://api-skynet-bj.fengkongcloud.com/v4/event";
        $params['accessKey'] = $this->smConfig['accessKey'];
        $params['appId'] = $this->smConfig['appId'];
        $params['eventId'] = 'preLogin';
        if ($header['os_name'] && in_array($header['os_name'], ['iPod touch','iPhone','iPad'])){
            $header['os_name'] = 'ios';
        }
        if ($header['os_name'] && strstr('Android',$header['os_name']) !== false){
            $header['os_name'] = 'Android';
        }
        $params['data'] = array(
            'tokenId'=> $this->user->generatedSmTokenId($phone),
            'ip'=> $ip,
            'deviceId'=> $deviceId,
            'isPhoneExist'=>0,
            'phone'=> md5($phone),
            'os'=> !empty($header['os_name']) ? $header['os_name'] : "",
            'appVersion'=> !empty($header['version_no']) ? $header['version_no'] : "1",
            'isTokenSeperate' => 0,
            'timestamp'=> time() * 1000,
            'phoneMd5'=> md5($phone),
        );
        write_log('smsCode', 'shumei params', $params);
        $res = curl_request($url ,$params ,'json','POST');
        return $res;
    }

    public function checkAudio($voice,$userId){
        $url = "http://api-audio-sh.fengkongcloud.com/audiomessage/v4";
        $params['accessKey'] = $this->smConfig['accessKey'];
        $params['appId'] = $this->smConfig['appId'];
        $params['eventId'] = 'audio';
        $params['type'] = 'POLITY_EROTIC_MOAN_ADVERT_DIRTY';
        $params['contentType'] = 'URL';
        $params['content'] = $voice;
        $params['data'] = [
            'tokenId' => (string)$userId
        ];
        $params['btId'] = 'audio-'.$userId;
        $res = curl_request($url ,$params ,'json','POST');
        return $res;
    }

    /**
     * 数美登录上报
     * @param $deviceId
     * @param $phone
     * @param $ip
     * @param $type
     * @return mixed
     */
    public function checkDeviceLoginRisk($deviceId ,$phone, $ip,$type){
        $header = $this->parse_app_UA();
        $url = "http://api-skynet-bj.fengkongcloud.com/v4/event";
        $params['accessKey'] = $this->smConfig['accessKey'];
        $params['appId'] = $this->smConfig['appId'];
        $params['eventId'] = 'login';

        if ($header['os_name'] && in_array($header['os_name'], ['iPod touch','iPhone','iPad'])){
            $header['os_name'] = 'ios';
        }
        if ($header['os_name'] && strstr('Android',$header['os_name']) !== false){
            $header['os_name'] = 'android';
        }
        $params['data'] = array(
            'tokenId'=> $this->user->generatedSmTokenId($phone),
            'isTokenSeperate' => 1,
            'type' => $type,
            'ip'=> $ip,
            'timestamp'=> time() * 1000,
            'deviceId'=> $deviceId,
            'phoneMd5'=> md5($phone),
            'os'=> !empty($header['os_name']) ? $header['os_name'] : "",
            'appVersion'=> !empty($header['version_no']) ? $header['version_no'] : "1"
        );
        write_log('shumeiLogin', 'login params', $params);
        $res = curl_request($url ,$params ,'json','POST');
        return $res;
    }

    public function saveDeviceRisk($deviceId ,$phone ,$response){
        $header = $this->parse_app_UA();
        $data = array(
            'guid'=> !empty($header['guid']) ? $header['guid'] : 0,
            'device_id'=>$deviceId,
            'version_no'=>!empty($header['version_no']) ? $header['version_no'] : '',
            'os_name' =>!empty($header['os_name']) ? $header['os_name'] : "",
            'phone'=>$phone,
            'risk_level'=>$response['riskLevel'],
            'score'=>$response['score']??0,
            'detail' => json_encode($response['detail']),
            'detail_json' => json_encode($response['detail']),
            'created_at'=>date('Y-m-d H:i:s')
        );
        return $this->user->insertDeviceRisk($data);
    }

    public function getGiftSwitch(){
        $user = $this->user->get_current_user();
        if(empty($user['user_id'])){
            return 0;
        }
        return $this->user->getGiftSwitch($user['user_id']);
    }
    public function setGiftSwitch(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('status', 'status', 'int', true, '开关状态');
            $this->I('user_id', 'user_id', 'int', true, '用户id');
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $data = $this->user->setGiftSwitch($this->requestData['user_id'] ,$this->requestData['status']);
        }while (false);

        return compact('code', 'msg', 'data');
    }
    //redis存储设备风险
    public function redisCacheDevice($key,$value,$expire_time = 300){
        return $this->user->redisCacheDevice($key,$value,$expire_time);
    }
    //redis获取设备风险
    public function redisCacheDeviceGet($key){
        return $this->user->redisCacheDeviceGet($key);
    }

    public function getUnionVestInfo(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('user_id', 'user_id', 'int', true, '用户id');
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $data = $this->user->get_user_from_db($this->requestData['user_id']);
        }while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     *添加/修改用户每日充值限制
     * */
    public function curdRechargeLimit()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('id', 'id', 'int', false);
            $this->I('user_id', 'user_id', 'int', true, '用户id');
            $this->I('value', 'value', 'int', true ,'限制金额');
            $this->I('opt_id', 'opt_id', 'int', true,'操作人id');
            $this->I('status', 'status', 'int', true,'状态');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $id = $this->requestData['id'] ?? 0;
            if(empty($this->requestData['id'])){
                unset($this->requestData['id']);
            }
            $res = $this->user->curdRechargeLimit(empty($id) ? 'insert' : 'update' ,$id ,$this->requestData);
            if(!$res){
                $code = Hint::ERR_FAIL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     *删除 用户每日充值限制
     */
    public function delRechargeLimit(){
        write_log('inner','inner',$this->requestData);

        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('id', 'id', 'int', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $res = $this->user->curdRechargeLimit('del' ,$this->requestData['id']);
            if(!$res){
                $code = Hint::ERR_FAIL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function getFinanceProxyStatus(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('user_id', 'user_id', 'int', false);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $financeProxy = $this->model_finance_proxy->getProxyInfoByUserId($this->requestData['user_id']);
            $data['status'] = ($financeProxy && $financeProxy['status'] == 1) ? 1 : 0;

        } while (false);

        return compact('code', 'msg', 'data');
    }
    public function getDefaultInfo(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $user = $this->user->get_current_user();
            if(empty($user)){
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $data['nickname'] = '甜枕用户'.$user['user_uid'];
            $portraits = $this->user->getDefaultPortrait();
            $portraits = array_column($portraits ,'portrait');
            $data['portrait'] = empty($portraits) ? '' : $portraits[array_rand($portraits)];
            $data['gender_portrait'] = [
                'nan' => getFullImageUrl("/portrait/nan.png"),
                'nv' => getFullImageUrl("/portrait/nv.png"),
            ];

	    $data['invite_code'] = '';
            if (!empty($user['invite_uid_new'])) {
		$inviteUid = $user['invite_uid_new'];
                $inviteUser = $this->user->get_users_by_ids([$inviteUid]);
		$inviteUser = array_column($inviteUser, null, 'user_id');
                $inviteUser = $inviteUser[$inviteUid] ?? [];
                if ($inviteUser && $inviteUser['is_open_code'] == 1) {
                    $data['invite_code'] = $inviteUser['code'];
                }

            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**判断用户是否已经完成实名认证
     * @return bool
     */
    public function is_certification(&$user_id){
        $user = $this->user->get_current_user();
        $user_id = $user['user_id'];
        if ($user['active_certify'] == 1) {
            return true;
        }
        return false;
    }

    /**是否成年
     * @return bool
     */
    public function is_audit(){
        $user = $this->user->get_current_user();
        $adult = $this->modelUserVerify->isAdult($user['user_id']);
        if ($adult == 1){
            return true;
        }
        return  false;
    }

    /**是否满16周岁
     * @return bool
     */
    public function isOverSixteen(){
        $user = $this->user->get_current_user();
        $adult = $this->modelUserVerify->isOverSixteen($user['user_id']);
        if ($adult == 1){
            return true;
        }
        return  false;
    }
    /**是否满18周岁
     * @return bool
     */
    public function isOverEighteen(){
        $user = $this->user->get_current_user();
        $adult = $this->modelUserVerify->isOverEighteen($user['user_id']);
        if ($adult == 1){
            return true;
        }
        return  false;
    }


    /**设置封号ip 前三位
     * @param $user_id
     */
    public function set_forbid_ip($user_id){
        $ip =$this->model_user_login_log->getLoginLog($user_id);
        if(!empty($ip)){
            $this->user->set_forbid_ip($user_id ,$ip);
        }
    }

    public function getRemark(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('remark_user_id', 'remark_user_id', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $user = $this->user->get_current_user();
            $remark_user_id = $this->requestData['remark_user_id'] ?? 0;
            $res = $this->user->getUserRemark($user['user_id'] ,$remark_user_id);
            if(empty($remark_user_id) &&!empty($res)){
                foreach ($res as $k=>$v){
                    $temp['user_id'] = $k;
                    $temp['remark_name'] = $v;
                    $data['list'][] = $temp;
                }
            }else{
                $data['remark_name'] = $res;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**换绑手机号
     * @return array
     */
    public function changeBindPhone(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('user_id', 'user_id', 'int', true);
            $this->I('phone', 'phone', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $user = $this->user->get_user($this->requestData['user_id'] ,true);
            if(empty($user)){
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $phone_user = $this->user->get_user_by_phone($this->requestData['phone']);
            if(!empty($phone_user)){
                $code = Hint::ERR_DATA_EXIST;
                $msg = '新手机号已绑定，id='.$phone_user['user_uid'];
                break;
            }
            $this->user->set_phone($this->requestData['user_id'] ,$this->requestData['phone']);
            $data['ori_phone'] = $user['phone'];
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function searchRecords(array $roomIdArr = [], int $userId = 0):int {
        if(empty($roomIdArr) || !$userId) return 0;

        // 最新的直播计划
        $roomIds = implode(',', $roomIdArr);
        $plans = $this->room->getRoomLivePlanByRoomIds($roomIds);
        if(!$plans) return 0;
        $userRegisterLogModel = new UserRegisterLog();
        $userRegisterLog = $userRegisterLogModel->getUserRegisterLog($userId);
        if(!$userRegisterLog) return 0;
        if($userRegisterLog->platform === 'kol') return 0;

        $batchInsertData = [];
        foreach($plans as $plan) {
            // 注册时间不在直播时间内不计算
            if($userRegisterLog->time < $plan['start_time'] || $userRegisterLog->time > $plan['end_time']) continue;

            $batchInsertData[] = [
                'plan_id' => $plan['id'],
                'join_user_id' => $userId,
                'create_time' => time()
            ];
        }

        if(!$batchInsertData) return 0;

        // 记录搜索记录,多次搜索记录多次
        return $this->room->batchInsertRoomLiveSearchRecords($batchInsertData);
    }

    /**
     * 获取用户标签列表
     */
    public function getUserTagsList() {
        $data['me'] = [];
        $data['other'] = [];
        foreach($this->user->userTags() as $item) {
            if(0 == $item['type']) {
                $data['me'][] = $item;
                continue;
            }
            $data['other'][] = $item;
        }
        return $data;
    }

    /**
     * 获取用户标签列表带标签分类
     */
    public function getUserTagsWithCat() {
        return  $this->user->userTagsWithCat();
    }

    /**
     * 设置用户标签
     */
    public function setUserTags(string $tags = '', int $type = 0) {
        $tags = explode(',', $tags);
        if(empty($tags)) return true;
        $curUser = $this->user->get_current_user();
        if ($type == 0) {//删除掉缓存
            (new UserTagServices())->deleteUserSelfTagCache($curUser['user_id']);
        }

        return $this->user->setUserTags($curUser['user_id'], $tags, ['tags', 'other_tags'][$type]);
    }

    public function createUserTag(array $data = []) {
        return $this->user->createUserTag($data);
    }

    public function updateUserTag(int $id, array $data = []) {
        return $this->user->updateUserTag($id, $data);
    }

    public function privateChatUserInfo(int $otherUserId): array {
        $this->checkToken();
        $returnData = [];
        $tagIs = 0;
        $otherTagIs = 0;
        $curUserInfo = $this->user->get_current_user();
        $otherUserInfo = $this->user->get_user($otherUserId);

        $returnData = collect($otherUserInfo)->only([
            'user_id',
            'user_uid',
            'nickname',
            'birthday',
            'gender',
            'tags',
            'other_tags',
            'images',
            'novice',
            'height',
            'occupation',
            'sign',
            'voice',
            'voice_time',
            'home',
            'affective_state'
            ])->toArray();

        // 处理标签
        $tags = $otherUserInfo['tags'];
        $otherTags = $otherUserInfo['other_tags'];
        if($heTags = array_intersect($otherUserInfo['tags'], $curUserInfo['other_tags'])) {
            $tagIs = 1;
            $tags = $heTags;
        }
        if($heOtherTags = array_intersect($otherUserInfo['other_tags'], $curUserInfo['tags'])) {
            $otherTagIs = 1;
            $otherTags = $heOtherTags;
        }

        $tagsList = $this->user->userTags();
        $tagsMap = array_column($tagsList, 'name', 'tag_id');
        $tags = array_map(function($tagId) use($tagsMap){
            return $tagsMap[$tagId];
        }, $tags);
        $otherTags = array_map(function($tagId) use($tagsMap) {
            return $tagsMap[$tagId];
        }, $otherTags);
        $returnData['tags'] = [
            'is' => $tagIs,
            'list' => $tags
        ];

        $returnData['other_tags'] = [
            'is' => $otherTagIs,
            'list' => $otherTags
        ];

        //开启房间
        $role_rooms = $this->room->get_role_rooms($otherUserId);
        $openRoomId = '';
        foreach ($role_rooms as $k => $v){
            if ($role_rooms[$k]['business_type'] == 1 && $role_rooms[$k]['certified'] == 0){
                    continue;
            }
            if(!$this->room->get_opened($v['room_id'])) {
                continue;
            }
            $openRoomId = $v['room_id'];
        }
        $returnData['open_room_id'] = $openRoomId;

        // 是否关注
        $returnData['is_follow'] = $this->model_friends->get_follow_exist($curUserInfo['user_id'], $otherUserId);
        return $returnData;
    }

    public function setOsVersion(int $userId = 0, string $versionNo = '') {
        return $this->model_user_login_log->setOsVersion($userId, $versionNo);
    }

    public function getOsVersion(int $userId = 0) {
        return $this->model_user_login_log->getOsVersion($userId);
    }

    public function addTestUser($user_id){
        return $this->user->addTestUser($user_id);
    }

    public function getTestUser(){
        $sysConfig = $this->system_service->get_config();
        Redis::del($this->redis_test_user_ids);
        $TestUser = isset($sysConfig['white_game_user']) ? $sysConfig['white_game_user']['value'] : 0;
        $TestUser=explode(",", $TestUser);
        foreach ($TestUser as $k=>$v){
            Redis::HSET($this->redis_test_user_ids,$v,'');
        }
        return $TestUser;
//        return $this->user->get_test_users();
    }

    public function delTestUser($user_id){
        return $this->user->delTestUser($user_id);
    }


    /**************************个性标签分类***********************/

    public function createUserTagsCat(array $data = []) {
        return $this->user->createUserTagsCat($data);
    }

    public function updateUserTagsCat(int $id, array $data = []) {
        return $this->user->updateUserTagsCat($id, $data);
    }
    public function delUserTagsCat(int $id, array $data = []) {
        return $this->user->delUserTagsCat($id, $data);
    }


    // add by zxiaofee
    public static function isLockedByLoginPasswordErr($phone) : bool {
        return User::isLockedByLoginPasswordErr($phone);
    }

    // add by zxiaofee
    public static function addLoginPasswordErrNum($phone) : int {
       return User::addLoginPasswordErrNum($phone);
    }

    public function getUserWealthBalance($userId){
        return $this->user->getUserWealthBalance( $userId);
    }

    //判断是否有同实名账户 如果是不能送礼物
    public function isSameIdCardNo($userIds){
        $userId = $this->get_current_user_id();
        $uids = array_merge([$userId], $userIds);
        $verifyInfos = (new UserVerify())->getIdCardNosByUserIds($uids);
        $verifyInfos = json_decode(json_encode($verifyInfos), true);
        $userVerify = array_column($verifyInfos, 'idcard_number', 'user_id');
        //送礼用户未实名认证
        if(empty($userVerify[$userId])) {
            return false;
        }
        foreach($userIds as $val) {
            if(empty($userVerify[$val])) {
                continue;
            }
            if($userVerify[$userId] == $userVerify[$val]) {
                return true;
            }
        }
        return false;

        // $fromIdCardNo = '';
        // $toIdCardNos = [];
        // foreach ($verifyInfos as $verify) {
        //     if ($verify->user_id == $userId) {
        //         $fromIdCardNo = $verify->idcard_number;
        //         continue;
        //     }
        //     array_push( $toIdCardNos, $verify->idcard_number);
        // }
        // if ($fromIdCardNo == ''){
        //     return false;
        // }

        // if (in_array($fromIdCardNo, $toIdCardNos)){
        //     return true;
        // }
        // return false;
    }

    /**
     * 读取用户未审核的头像
     * @param $userId
     * @param $images
     * @return array
     */
    private function getContentCheckAvatar($userId, $images)
    {
        // 用户本人，显示未审核的头像
        $checks = $this->contentCheckModel->getContentCheckListByUserIdAndCheckObj($userId, [8]);
        $checkImages = [];
        if (!empty($checks)) {
            $checkImages = array_filter(array_column($checks, 'content'));
            //过滤掉重复图片，审核表和用户表头像路径可能不一样。所以需要验证文件名
            if (!empty($images)) {
                foreach ($checkImages as $key => $img) {
                    $file = basename(trim($img));
                    foreach ($images as $uimg) {
                        $ufile = basename(trim($uimg));
                        if ($file == $ufile) {
                            unset($checkImages[$key]);
                        }
                    }
                }
            }
        }
        return array_merge($checkImages);
    }

    /**
     * 用户简易注销
     * 简易注销是指仅删除用户手机号以及认证信息，不会删除软件中发布的任何内容。
     */
    public function simpleAccountCancel($userId){

        $uinfo = $this->user->get_user($userId,true);

        if(empty($uinfo)){
            return Hint::USER_IS_NOT_EXIST;
        }

        $phone = empty($uinfo['phone']) ? "" : $uinfo['phone'];
        $result = $this->UserAccountCancelModel->simpleCancelUser($userId,$phone);

        return $result;


    }

    /**
     * 房间搜索过滤
     * $data array 数据体
     * $userUid int 用户id
     * return array
     */
    private function roomSearchFilter($data, $userUid)
    {
        if (empty($data['list'])) {
            return $data;
        }

        //过滤掉最多金房间
        $maximumGoldRoomIds = (new MaximumGoldRoomServices())->getRoomIds();

        //最多金房间不存，则跳过
        if (empty($maximumGoldRoomIds)) {
            return $data;
        }

        //读取最多金限制用户id
        $roomBlacklist = (new SystemConfig())->getRoomBlockConfig();
        $maximumGoldBlackUserUids = $roomBlacklist['maximum_gold_block_user'] ?? [];

        //这些用户不能显示最多金房间
        if (!in_array($userUid, $maximumGoldBlackUserUids)) {
            return $data;
        }

        foreach ($data['list'] as $key => $room) {
            if (in_array($room['room_id'], $maximumGoldRoomIds)) {
                unset($data['list'][$key]);
            }
        }
        $data['list'] = array_merge($data['list']);
        return $data;
    }


    /**
     * 检查用户是否可以被邀请
     */
    public function checkUserCanBeInvite($userId, $inviteUserId){
        $userInfo = $this->user->get_user($userId,true);
        //已邀请
        if(!empty($userInfo['invite_uid'])) {
            return false;
        }
        //不可被邀请
        $check = $this->user->checkInNoInvite($userInfo['phone']);
        if($check) {
            return false;
        }
        //邀请用户信息
        $inviteUserInfo = $this->user->get_user($inviteUserId,true);
        //同个手机号
        if($userInfo['phone'] == $inviteUserInfo['phone']) {
            return false;
        }
        //同一设备
        if($userInfo['guid'] == $inviteUserInfo['guid']) {
            return false;
        }

        return true;
    }

    /**
     * 检查手机唯一标识是否存在
     */
    public function checkGuidHas($userId, $guid){
        $userList = $this->user->getUserByGuid($guid);
        if(!empty($userList)) {
            $userIds = array_unique(array_column($userList, 'user_id'));
            if(count($userIds) > 1) {
                return false;
            }
        }

        return true;
    }

    //批量获取获取用户信息
    public function getUserInfoByUserIds($userIds){
        $list = $this->user->getUserInfoByIds($userIds);

        $data = [];
        foreach($list as $val) {
            $images = json_decode($val['portrait'],true) ?? [];
            if(empty($images[0])) {
                $images = User::USER_DEFAULT_IMAGE;
            }

            $item['user_id'] = $val['user_id'];
            $item['uuid'] = $val['uuid'];
            $item['nickname'] = $val['nickname'];
            $item['sex'] = $val['gender'];
            $item['birthday'] = $val['birthday'];
            $item['soliloquy'] = $val['soliloquy'];
            $item['head_image'] = build_url($images[0]);
            $item['mood_id'] = $val['mood_id'];
            $item['mood_name'] = '';
            $item['mood_image'] = '';
            $item['identity_role'] = $val['identity_role'];
            $item['identity_status'] = $val['identity_status'];

            $data[$val['user_id']] = $item;
        }

        return $data;
    }

    //获取用户拥有公会id
    public function getUnionInfoToUnUserId($userId){
        $unionId = $this->modelUnion->getUnionInfoToUnUserId($userId);

        return $unionId;
    }

    //编辑资料
    public function identityToVerify($userId, $voice, $voice_time, $sign)
    {
        $updata = [];
        $updata['voice'] = $voice;
        $updata['voice_time'] = $voice_time;
        $updata['sign'] = $sign;
        $updata['identity_role'] = 2;
        $updata['identity_status'] = 2;

        $ret = $this->user->updateUserIdentity($userId, $updata);

        return $ret;
    }

    //主播审核
    public function anchorVerify($userId, $identity_status)
    {
        $updata = [];
        // $updata['identity_role'] = 2;
        //通过 忙碌中
        if($identity_status == 3) {
            $updata['identity_status'] = $identity_status;
            $ret = $this->user->updateUserIdentity($userId, $updata);

        }
        //审核拒绝
        if($identity_status == 4) {
            $updata['identity_status'] = $identity_status;
            $ret = $this->user->updateUserIdentity($userId, $updata);
        }

        return 1;
    }

    //用户性别重置
    public function genderReset($userId)
    {
        $updata = [];
        $updata['gender'] = 3;
        $ret = $this->user->updateUserByData($userId, $updata);

        //用户退出登录
        $this->user->del_current_user();

        return 1;
    }

    //主播身份状态编辑
    public function identityStatusUpdate($userId, $identityStatus, $where=[])
    {
        $updata = [];
        $updata['identity_status'] = $identityStatus;

        $ret = $this->user->updateUserIdentity($userId, $updata, $where);
        $this->user->get_user($userId);

        return $ret;
    }

    //主播列表
    public function identityList($userId)
    {
        //获取用户黑名单
        $notUserIds = $this->model_friends->getBlockUserId($userId);
        $search = new Search();

        $result = $search->searchUserIdentity(0, 6, $notUserIds);

        $list = [];
        foreach($result as $val) {
            unset($val['phone']);
            unset($val['create_timestamp']);
            $list[] = $val;
        }
        return ['list'=>$list];
    }

    //后台更改主播资料状态
    public function changeChatFriend($id,$status){
        $status = $this->user->changeStatus($id,$status);
        return $status;
    }

    /**
     * 检查用户是否送给指定用户礼物
     */
    public function checkUserGetGift($fromUserId, $toUserId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            if(empty($fromUserId) || empty($toUserId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $status = 2;//状态 1=送过 2=没送过
            $info = $this->gift->getGiftStreamFirstFromUserId($fromUserId, $toUserId);
            if(!empty($info)) {
                $status = 1;
            }
            $data['status'] = $status;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 搜索用户
     * */
    public function searchUser($keywords, $page, $limit)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $userList = $this->user->keywordsSearch($keywords, $page, $limit);
            $userList = empty($userList['list']) ? [] : $userList['list'];
            $data['list'] = $userList;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取用户身份
     * */
    public function getUserIdentity($toUserId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $data['user_type'] = 1;//1=用户 2=主播
            $data['union_id'] = 0;
            $data['un_user_id'] = 0;

            //根据用户id获取所属认证公会
            $unionInfo = $this->modelUnion->getUserUnionInfo($toUserId);
            if(!empty($unionInfo)) {
                $data['user_type'] = 2;
                $data['union_id'] = $unionInfo['id'];
                $data['un_user_id'] = $unionInfo['un_user_id'];
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取主播收礼排行榜
     * */
    public function getAnchorAcceptGiftRank($toUserId, $type)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = ['list'=>[]];
        $ymd = date('Ymd');

        do {
            //根据用户id获取所属认证公会
            $unionInfo = $this->modelUnion->getUserUnionInfo($toUserId);
            if(empty($unionInfo)) {
                break;
            }
            //主播收礼实时榜单
            if($type == 1) {
                $cacheKey = $this->anchorAcceptGiftTimeRankKey.$toUserId;
            }
            //主播收礼每日榜单
            if($type == 2) {
                $cacheKey = $this->anchorAcceptGiftDayRankKey.$toUserId.':'.$ymd;
            }
            if(empty($cacheKey)) {
                break;
            }
            $list = Redis::zrevrange($cacheKey, 0, -1);
            if(empty($list)) {
                break;
            }
            $userList = $this->user->get_users_by_ids($list);
            $userList = array_column($userList, null, 'user_id');

            $ListEx = [];
            $num = 1;
            foreach($list as $userId) {
                $score = Redis::ZSCORE($cacheKey, $userId);

                $item = [];
                $item['num'] = $num;
                $item['user_id'] = $userId;
                $item['score'] = (int) $score;
                $item['gender'] = (int) ($userList[$userId]['gender'] ?? '');
                $item['nickname'] = $userList[$userId]['nickname'] ?? '';
                $item['user_uid'] = $userList[$userId]['user_uid'] ?? '';
                $item['image'] = build_image($userList[$userId]['images'][0] ?? '');

                $ListEx[] = $item;
                $num++;
            }
            $data['list'] = $ListEx;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 删除主播收礼实时榜单
     * */
    public function delAnchorAcceptGiftRank($userId, $toUserId, $roomId, $userIds)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //根据用户id获取所属认证公会
            $unionInfo = $this->modelUnion->getUserUnionInfo($toUserId);
            if(empty($unionInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //可操作榜单删除的
            $flag = 0;
            //主播本人
            if($userId == $toUserId) {
                $flag = 1;
            }
            //主播归属公会的公会长
            if($userId == $unionInfo['un_user_id']) {
                $flag = 1;
            }
            //主播归属公会房间的主持
            if($flag == 0) {
                //房间所属公会
                $roomUnionInfo = $this->modelUnion->getUnionByRoomId($roomId);
                if($unionInfo['id'] == $roomUnionInfo['id']) {
                    //房间主持
                    $key = $this->redis_room_hostmicro_key . $roomId;
                    $roomUserId = Redis::HGET($key, "user_id");
                    if(!empty($roomUserId) && $roomUserId==$userId) {
                        $flag = 1;
                    }
                }
            }

            if($flag == 1) {
                //主播收礼实时榜单
                $cacheKey = $this->anchorAcceptGiftTimeRankKey.$toUserId;
                foreach($userIds as $item) {
                    Redis::ZREM($cacheKey, $item);
                }
            }else{
                $code = Hint::PARAM_ERROR;
                $msg = '您暂无删除权限，如有需要请与主播本人沟通';
                break; 
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 记录用户私信数据
     */
    public function saveUserMsg($fromUserId, $content, $toUserId, $roomId, $placeType)
    {
        $time = time();
        $ymd = date('Ymd', $time);
        do {
            if(empty($content)) {
                break;
            }

            //发信用户公会
            $unionInfo = $this->modelUnion->getUserUnionInfo($fromUserId);
            $unionId = empty($unionInfo['id']) ? 0 : $unionInfo['id'];

            //收信用户信息
            $userData = $this->user->get_user($toUserId, true);
            $userCreateTime = $userData['create_timestamp'];

            //锁
            $lockKey = 'USERMSG:'.$fromUserId.':'.$toUserId;
            if (!redis_lock($lockKey, 5)){
                break;
            }

            //是否存在
            $data = [
                'ymd' => $ymd,
                'from_user_id' => $fromUserId,
                'union_id' => $unionId,
                'to_user_id' => $toUserId,
            ];
            $info = $this->user->getUserMsg($data);
            if(empty($info)) {
                $data['if_new'] = (date('Ymd', $userCreateTime) == $ymd) ? 1 : 0;
                $id = $this->user->createUserMsg($data);
            }else{
                $id = $info['id'];
            }
            //累加
            $this->user->incrUserMsg($id, 'sms_num', 1);
            redis_unlock($lockKey);

            //记录内容
            $this->userBlacklistService->checkSaveUserMsg($fromUserId, $content, $toUserId, $roomId, $placeType);

        } while (false);
    }

    /**
     * 用户是否在黑名单中
     */
    public function getBlackListByUserId($userId)
    {
        //用户是否在黑名单中
        $ifBlack = $this->userBlacklistModel->getBlackListByUserId($userId);
        if($ifBlack) {
            return 1;
        }
        return 0;
    }
    /**
     * 用户未消费钻石，金币以及背包礼物数量
     */
    public function getUserGift()
    {
        $this->userWallet->getUserWalletCount();
    }

    /**
     * wap 获取用户注册时间
     * @return mixed|null
     */
    public function user_regInfo($userId){
        $createtime=$this->user->get_usercreattime($userId);
        //时间差
        $time_difference=time()-$createtime;
        //相差天数
        $difference_day=round($time_difference/(60*60*24));
        return $difference_day;
    }
    /**
     * wap 获取用户流水
     * @return mixed|null
     */
    public function getGiftData($userId){
        $getGiftData=$this->user->getGiftData($userId);
        return empty($getGiftData)?0:$getGiftData;
    }

    /**
     * 获取首冲礼包
     * @param $userId
     * @return array
     */
    public function getUserFirstRechargeList($userId)
    {
        $firstRechargeData = array_column($this->firstRechargeData, null, "first_recharge_id");
        foreach ($firstRechargeData as &$firstRechargeDatum) {
            //商品数据
            $firstRechargeDatum["goods_data"] = [];
            $goods_list_id = explode(',', $firstRechargeDatum["goods_list"]);
            $goods_list_sku_id = explode(',', $firstRechargeDatum["goods_list_sku"]);
            $goods_list = $this->mallGoods->getGoodsByGoodIds($goods_list_id);
            if (!empty($goods_list)) {
                $firstRechargeDatum["goods_data"] = $goods_list;
                //商品sku数据
                foreach ($firstRechargeDatum["goods_data"] as $k => &$firstRechargeDatumItem) {
                    $imgSource = getPicDomain();
                    if (!empty($firstRechargeDatumItem['small_img'])) {
                        $firstRechargeDatumItem['small_img'] = $imgSource . $firstRechargeDatumItem['small_img'];
                    }
                    if (!empty($firstRechargeDatumItem['big_img'])) {
                        $firstRechargeDatumItem['big_img'] = $imgSource . $firstRechargeDatumItem['big_img'];
                    }
                    if (!empty($firstRechargeDatumItem['animate_resource'])) {
                        $firstRechargeDatumItem['animate_resource'] = $imgSource . $firstRechargeDatumItem['animate_resource'];
                    }
                    if (!empty($firstRechargeDatumItem['animate_resource_small'])) {
                        $firstRechargeDatumItem['animate_resource_small'] = $imgSource . $firstRechargeDatumItem['animate_resource_small'];
                    }
                    $firstRechargeDatumItem["sku"] = $this->mallGoods->getSkuData((int)$firstRechargeDatumItem["goods_id"],(int)$goods_list_sku_id[$k]);
                }
            }
        }

        $user_first_recharge = $this->user->get_user_first_recharge($userId);
        if (!isset($user_first_recharge['first_recharge_status'])) {
            $user_first_recharge['first_recharge_status'] = true;
            $firstRechargeData = Hint::USER_NOT_EXIST;
        }

        if ($user_first_recharge['first_recharge_status'] == false) {
            $firstRechargeData = [];
        }
        //查询购买记录
        $record = $this->userFirstRechargeModel->findUserFirstRechargeRecordList($userId);
        if (!empty($record)) {
            foreach ($record as $k) {
                if ($k == $firstRechargeData[$k["first_recharge_id"]]) {
                    $firstRechargeData[$k["first_recharge_id"]]["purchase"] = false;
                }
            }
        }
        if ($firstRechargeData == Hint::USER_NOT_EXIST) {
            $user_first_recharge['first_recharge_status'] = true;
            $firstRechargeData = [];
        }
        $return = [
            "userFirstRechargeStatus" => $user_first_recharge['first_recharge_status'],
            "firstRechargeData" => array_values($firstRechargeData),
        ];


        return $return;
    }

    /**
     * 首冲礼包赠送商品
     * @param $userId
     * @param $firstRechargeId
     * @param $money
     * @param $payChannel
     * @return void
     */
    public function setBackFirstRecharge($userId,$firstRechargeId,$money,$payChannel)
    {
        //查询是否购买过首冲礼包
        $firstRecharge = $this->userFirstRechargeModel->findUserFirstRechargeRecord($userId,$firstRechargeId);
        if (empty($firstRecharge)) {
            $firstRechargeData = array_column($this->firstRechargeData, null, "first_recharge_id");
            //记录首冲礼包
            $record = [
                "first_recharge_id" => $firstRechargeData[$firstRechargeId]["first_recharge_id"],
                "user_id" => $userId,
                "money" => $money,
                "diamond" => $firstRechargeData[$firstRechargeId]["diamond"],
                "goods_list" => $firstRechargeData[$firstRechargeId]["goods_list"],
                "goods_list_sku" => $firstRechargeData[$firstRechargeId]["goods_list_sku"],
                "pay_channel_id" => $payChannel,
                "created_at" => time(),
            ];
            $this->userFirstRechargeModel->addUserFirstRechargeRecord($record);
            //发放商品
            $goods = explode(",", $firstRechargeData[$firstRechargeId]["goods_list"]);
            $sku = explode(",", $firstRechargeData[$firstRechargeId]["goods_list_sku"]);
            $goodsList = array_map(function ($g, $s) {
                return ["goods" => $g, "sku" => $s];
            }, $goods, $sku);
            foreach ($goodsList as $value) {
                $_goods = $this->mallGoods->get_goods((int)$value["goods"]);
                $_sku = $this->mallGoods->getSkuBySkuId((int)$value["sku"]);
                $timeLimit = $_sku["time_limit"] * 86400;
                //赠送商品
                $this->mallGoods->shoppingAct( 11,
                    $userId,
                    $_goods["goods_id"],
                    $_goods["goods_name"],
                    $_goods["goods_type"],
                    $value["sku"],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2);
            }
            //记录首冲礼包日志
            write_log("first_recharge_goods", "first_recharge_log: ", json_encode($record,true));
            //查询用户首冲资格
            $count = $this->userFirstRechargeModel->findUserFirstRechargeRecordCount($userId);
            if ($count >= 3) {
                $this->user->updateFirstRechargeStatus($userId,0);
            }
        }
    }
}
